2

Consider the following Typescript code:

module demoAppModule{
    'use strict';

    export module nest{
        export var hello = function () {
            alert('Hello!');
        };
    }
}

demoAppModule.nest.hello();

After transpiling we have the following javascript code:

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

Why is this line generated? It hurts my eyes.

var nest = demoAppModule.nest;
4

1 回答 1

1

简短回答:它需要在本地访问模块变量。例如

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,例如 notice var x

// TypeScript 
module x{export var foo;}
// Generated JavaScript 
var x;
(function (x) {
    x.foo;
})(x || (x = {}));

但是,当您在模块内 + 导出模块时,var需要将其添加到其中,outermodule.innermodule因此您无需var innermodule预先进行操作。您将其添加到outermodule然后创建一个局部变量以指向innermodule您可以在生成的 javascript 中看到的:

// 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();
于 2013-08-26T08:03:21.317 回答