理解Typescript编译器生成的Javascript [英] Understanding Javascript generated by Typescript compiler

查看:127
本文介绍了理解Typescript编译器生成的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我输入这个简单的打字稿代码:

if i type this simple typescript code:

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

我的问题:上述有何不同:

my question: how does above differ from:

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

如果没有差异,那么上面就更简单了

if no difference, then above is much simpler

推荐答案

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

What you see is The design pattern - Module. See more here:

  • JavaScript Module Pattern: In-Depth (written by ben cherry)

引用:

模块导出


有时你不只是想使用全局变量,而是想要声明它们。我们可以通过使用匿名函数的返回值导出它们来轻松完成此操作。这样做将完成基本模块模式,所以这是一个完整的例子:

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




请注意,我们已经声明了一个名为MODULE的全局模块,其中有两个公共属性:名为MODULE.moduleMethod的方法和名为MODULE.moduleProperty的变量。此外,它使用匿名函数的闭包来维护私有内部状态。此外,我们可以使用上面学到的模式轻松导入所需的全局变量。

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.

另一个非常基本的资源是:

Another really fundamental resource is:

  • Learning JavaScript Design Patterns (A book by Addy Osmani)

引用:


在JavaScript中,模块模式用于以这种方式进一步模拟类的概念我们能够在单个对象中包含公共/私有方法和变量,从而将特定部分与全局范围隔离开来。这会导致我们的函数名称与页面上其他脚本中定义的其他函数冲突的可能性降低...

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...

在链接中查看更多信息

这篇关于理解Typescript编译器生成的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆