3 ms·
In the playground, the following: class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() {
by Aardwolf 12y ago
In the playground, the following:
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
Compiled to the following:
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
So I have a question about this: what is the reason why it doesn't become the following instead?
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
In other words, why is the extra function put around it? There must be a good reason... Thanks!
- coldtea 12y agoIt's a closure, so stuff doesn't escape unless it's explicitly returned. It doesn't seem to be needed here, but their transpiler could use the same structure for more evolved classes/module too, where it would make sense.
- Too 12y agoCheck the modules sample, there a module is passed as argument to the self executing function to which the newly created Greeter class is added, without leaking any temporary Greeter variables to the global namespace. I guess it's just designed to generate as similar code as possible for both the module and non-module cases.