gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:31:23 25 4
gpt4 key购买 nike

如果我输入这个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com