我一直在玩TypeScript,我注意到它遵循JS的特定风格。
以下TypeScript:
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
像这样生成JS:
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
IIFE有什么好处?为什么我需要在新范围内将我的方法附加到我的原型?
如果我继续这样做,我会失去任何东西:
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
(正如我一直所做的)相反?