【问题标题】:why the code is converted in this way?为什么代码是这样转换的?
【发布时间】:2013-01-05 09:14:38
【问题描述】:

最近开始学习 Typescript。我对从 Typescript 到 Javascript 的转换有疑问。

为什么是这个代码:

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;
})();

为什么会这样转换?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

私有变量和函数在运行时未设为私有的原因是性能下降。创建 TypeScript 是为了支持在浏览器和服务器上运行的大型程序 - 因此性能是一个大问题。

TypeScript 发布时,我问了同样的问题,Anders 回答了。你可以view the discussion on Codeplex

【讨论】:

  • 我不明白为什么我们应该期待运行时私有变量和函数。从某种意义上说,大多数强类型语言没有“真正的”运行时私有成员,因为您仍然可以通过反射访问它们。 JavaScript 仅在某种意义上是特殊的,它使这种反射非常非常容易。
  • 我认为这个问题是相关的,因为在 JavaScript 中,您可以使用作用域将其设为私有,但性能不高。
  • 在测试中,我所做的 - 两个解决方案之间没有真正花费的时间不同。但是在使用闭包的解决方案中,我们有一个私有方法。添加选项会很好,这确实允许使用私有方法。
猜你喜欢
  • 2013-01-07
  • 2015-03-12
  • 2015-07-07
  • 2013-02-27
  • 2021-10-06
  • 2016-09-24
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多