[英]Typescript generating redundant variable
考慮以下打字稿代碼:
module demoAppModule{
'use strict';
export module nest{
export var hello = function () {
alert('Hello!');
};
}
}
demoAppModule.nest.hello();
編譯后,我們具有以下javascript代碼:
var demoAppModule;
(function (demoAppModule) {
'use strict';
(function (nest) {
nest.hello = function () {
alert('Hello!');
};
})(demoAppModule.nest || (demoAppModule.nest = {}));
var nest = demoAppModule.nest;
})(demoAppModule || (demoAppModule = {}));
demoAppModule.nest.hello();
為什么會生成此行? 傷了我的眼睛。
var nest = demoAppModule.nest;
簡短的回答:需要在本地訪問模塊變量。 例如
module demoAppModule{
'use strict';
export module nest{
export var hello = function () {
alert('Hello!');
};
}
// The following would not be possible without that line
console.log(nest.hello);
}
demoAppModule.nest.hello();
更長的答案:它類似於在模塊之前添加的var,例如,注意var x
:
// TypeScript
module x{export var foo;}
// Generated JavaScript
var x;
(function (x) {
x.foo;
})(x || (x = {}));
但是,當您在模塊內部+導出模塊時,需要將var
添加到outermodule.innermodule
因此您無需預先進行var innermodule
。 您將其添加到outermodule
,然后創建一個本地變量以指向您可以在生成的javascript中看到的innermodule
:
// Notice var here
var demoAppModule;
(function (demoAppModule) {
'use strict';
// Notice no var here
(function (nest) {
nest.hello = function () {
alert('Hello!');
};
})(demoAppModule.nest || (demoAppModule.nest = {}));
// Notice var assinged afterwards
var nest = demoAppModule.nest;
// The following would not be possible without that line
console.log(nest.hello);
})(demoAppModule || (demoAppModule = {}));
demoAppModule.nest.hello();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.