2

次の Typescript コードを検討してください。

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;
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 xモジュールの前に追加された var に似ています。

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

ただし、モジュール内にいる場合はモジュールをエクスポートするvar必要があるため、事前outermodule.innermoduleに行う必要はありませんvar innermodule。それをに追加してから、生成された JavaScript で確認できる をoutermodule指すローカル変数を作成します。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();
于 2013-08-26T08:03:21.317 に答える