如果我创建一个名为 test
的简单 TypeScript 模块
,它将如下所示:
module test
{
export class MyTest {
name = "hello";
}
}
生成的 JavaScript
创建了一个如下所示的 IIFE
:
var test;
(function (test) {
var MyTest = (function () {
function MyTest() {
this.name = "hello";
}
return MyTest;
})();
test.MyTest = MyTest;
})(test || (test = {}));
我不明白的是 IIFE
末尾包含 function
参数的以下行的目的是什么:
(test || (test = {}));
结果函数还接受参数test
:
(function (test) {
我理解当使用参数传递一个像 })(jquery);
这样的 'jQuery
对象时,结果函数可以采用像 这样的别名(function ($) {
。但是我只是没有看到 (test || (test = {}));
参数的目的。
我明白 test.MyTest = MyTest;
公开了公共(public)方法 MyTest
,但为什么 (test || (test = {}));
以及这些参数是如何工作的?
最佳答案
它允许您使模块开放式。例如
(function (test) {
var MyTest = (function () {
function MyTest() {
this.name = "hello";
}
return MyTest;
})();
test.MyTest = MyTest;
})(test || (test = {}));
(function (test) {
var SecondTest = (function () {
function SecondTest() {
this.name = "hello";
}
return SecondTest;
})();
test.SecondTest= SecondTest;
})(test || (test = {}));
第一次 test
将是 undefined
并因此被分配 {}
。下一次它已经被定义,这就是我们用 SecondTest
关于javascript - 来自 TypeScript 模块的 JavaScript IIFE 中的默认参数的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901282/