【问题标题】:Typescript generating redundant variable打字稿生成冗余变量
【发布时间】:2013-08-26 07:13:00
【问题描述】:

考虑以下 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;

【问题讨论】:

  • 那行对我来说似乎完全没用。我能想到的唯一原因是编译器认为参数nest必须在函数hello之前定义,但是赋值发生在最底部,然后什么都不做。

标签: javascript compilation typescript


【解决方案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,例如通知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();

【讨论】:

  • 谢谢。阅读本文后,我意识到如果我之后使用嵌套,就像您示例中的日志记录一样,它看起来就不会那么不必要了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2019-01-02
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
相关资源
最近更新 更多