Javascript 为什么代码以这种方式转换?
最近开始学习打字。我对从Typescript到Javascript的转换有疑问 为什么要使用此代码:Javascript 为什么代码以这种方式转换?,javascript,typescript,Javascript,Typescript,最近开始学习打字。我对从Typescript到Javascript的转换有疑问 为什么要使用此代码: class Greeter { greeting: string; private hello(){ return this.greeting; } public hi(){ alert(this.hello()); } constructor(message: string) { this.gree
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;
}
}
转化为
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;
})();
不是这个吗
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;
})();
为什么会这样转换?私有变量和函数在运行时没有变为私有的原因是性能受到影响。TypeScript是为了支持在浏览器和服务器上运行的大型程序而创建的,因此性能是一个巨大的问题
当TypeScript发布时,我问了同样的问题,安德斯回答了。您只能在编译时进行访问检查。。我不明白为什么我们应该期望运行时私有变量和函数。在某种意义上,大多数强类型语言没有“真正的”运行时私有成员,因为您仍然可以通过反射访问它们。JavaScript只是在某种意义上很特别,它使这种反射非常容易。我认为这个问题是相关的,因为在JavaScript中,你可以使用作用域将其私有化,但它的性能没有那么好。在测试中,我确实做到了——两种解决方案之间的时间并没有真正花费。但在闭包的解决方案中,我们有一个私有方法。添加选项会很好,这确实允许使用私有方法。