0

Here is the typescript code and the corresponding JavaScript that is generated. Why did microsoft choose to use this.greeting instead of using a var and hiding the variable from accessing from outside in the generated js code? changing the property to private in typescript only throws compilation error, but the generated js code is ditto

//typescript code
class Greeter {
    greeting: string; //why is this not private by default???
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
console.log(greeter.greeting); //why the heck is 'greeting accessible'

//Generated javascript as follows
var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message; //this should have been a var ????
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
}());
var greeter = new Greeter("world");
console.log(greeter.greeting); //why the heck is 'greeting accessible'
scriptuser
  • 55
  • 2
  • 9

2 Answers2

2

There was a great deal of discussion around the private keyword early on. The TypeScript team considered the performance cost of this in a very large application and they believed it would be too great.

Although the performance cost would be negligible in many applications, there are cases where TypeScript is used to build multi-million LOC applications and they would effectively be prevented from using private variables if the compiled JavaScript actually attempted to hide the variable.

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

You can see my version of your question on the original TypeScript Codeplex site (along with Anders' Hejlsberg's answer).

Fenton
  • 241,084
  • 71
  • 387
  • 401
1

This is true that using var makes the variable just visible in given scope but the problem with that would be when you need to extend the class then there is no way to access that var in new class.

Morteza Tourani
  • 3,506
  • 5
  • 41
  • 48