Why doesn't TypeScript encapsulate the private variables?
Given the following TypeScript:
private engine: string;
constructor(engine: string) {
this.engine = engine;
}
start() {
console.log('Starting engine ' + this.engine);
}
}
var car = new Car("Fiat");
car.start();
When I compile I get the following JavaScript:
var Car = (function () {
function Car(engine) {
this.engine = engine;
}
Car.prototype.start = function () {
console.log('Starting engine ' + this.engine);
};
return Car;
}());
var car = new Car("Fiat");
car.start();
The engine
variable is public. Why doesn't TypeScript produce something more like:
var Car = (function () {
var _engine;
function Car(engine) {
_engine = engine;
}
Car.prototype.start = function () {
console.log('Starting engine ' + _engine);
};
return Car;
}());
For performance reasons. From Anders, "The problem with using constructor function local variables for private storage is that they can't be accessed from functions on the prototype object (which is what methods on a class become in the generated JavaScript). Instead you need to create local function objects and that consumes a lot more memory... As you can see, you need to create one function object per instance instead of a single function object shared by all instances through the prototype." See here for a discussion: https://typescript.codeplex.com/discussions/397651
or here, "patterns for enforced private members in JavaScript have a lot of performance overhead. TypeScript is mainly targeting large applications, so compiling to code with performance overhead is not optimal"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With