Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't TypeScript encapsulate private fields? [duplicate]

Tags:

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;
}());
like image 295
BanksySan Avatar asked Apr 17 '16 18:04

BanksySan


1 Answers

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"

like image 193
RationalDev likes GoFundMonica Avatar answered Sep 28 '22 01:09

RationalDev likes GoFundMonica