2

Recently started studying Typescript. I have questions about the conversion from Typescript to Javascript.

Why this code:

class Greeter {
    greeting: string;
    private hello(){
        return this.greeting;
    }
    public hi(){
        alert(this.hello());
    }
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

converted to

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.hello = function () {
        return this.greeting;
    };
    Greeter.prototype.hi = function () {
        alert(this.hello());
    };
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

not this?

var Greeter = (function () {
    var hello = function(){
       return this.greeting;
    }
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.hi = function () {
        alert(hello.call(this));
    };
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Why is it converts that way?

Ian
  • 50,146
  • 13
  • 101
  • 111
mantsevich
  • 41
  • 5
  • Access checks only during compile time. http://stackoverflow.com/questions/12713659/typescript-private-members – Damask Jan 22 '13 at 07:31

1 Answers1

6

The reason private variables and functions are not made private at runtime is because of the performance hit. TypeScript was created to support large programs running in the browser and on the server - so performance is a massive concern.

I asked the same question when TypeScript was released and Anders answered. You can view the discussion on Codeplex.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • I don't see why we should expect runtime private variables and functions. In a sense most strongly typed languages do not have "real" runtime private members because you can stil access them with reflection. JavaScript is only special in the sense, that it makes this kind of reflection very very easy. – Attila Kun Jan 22 '13 at 18:31
  • 1
    I think the question is relevant because in JavaScript you can make it private using scope, but it isn't as performant. – Fenton Jan 22 '13 at 18:36
  • In the tests, that I did - time not really spend differs between the two solutions. But in solution with the closures we have a private method. It would be nice to add options, that really allowed use the private methods. – mantsevich Jan 24 '13 at 08:55