javascript - 理解 Typescript 编译器生成的 Javascript

标签 javascript typescript

如果我输入这个简单的 typescript 代码:

class Point2D
{
    constructor(public x: number, public y: number)
    {
    }
} 

并查看生成的js:

var Point2D = (function () {
    function Point2D(x, y) {
        this.x = x;
        this.y = y;
    }
    return Point2D;
})();

我的问题:以上与以下有何不同:

function Point2D(x, y) {
    this.x = x;
    this.y = y;
}

如果没有区别,那么上面就简单多了

最佳答案

您看到的是设计模式 - 模块。在这里查看更多信息:

引用:

模块导出

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value. Doing so will complete the basic module pattern, so here’s a complete example:

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

Notice that we’ve declared a global module named MODULE, with two public properties: a method named MODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal state using the closure of the anonymous function. Also, we can easily import needed globals, using the pattern we learned above.

另一个真正基础的资源是:

引用:

模块模式

In JavaScript, the Module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of our function names conflicting with other functions defined in additional scripts on the page...

在链接中查看更多信息

关于javascript - 理解 Typescript 编译器生成的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072525/

相关文章:

javascript - jmHighlight 有问题

javascript - 带有递归 Ajax 的 Jquery Promise

node.js - typescript Cipher.getAuthTag 不存在

html - 使用 typeScript 滚动到我的 webView 上的 x,y 坐标

angular - Angular 动态形式的单选按钮

javascript - 如何在新的 div 中追加 li

javascript - jQuery .hover 更改非子元素的 css

javascript - Flowtype - 如何为类工厂编写声明,例如 Backbone 模型?

javascript - 为什么这个对象变量未定义?

Angular 4 - *ngComponentOutlet 需要澄清