如何从 TypeScript 中的父模块访问变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12883520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:15:36  来源:igfitidea点击:

How to access variable from parent module in TypeScript?

javascripttypescript

提问by Wouter de Kort

If I have this TypeScript code:

如果我有这个 TypeScript 代码:

module Foo
{
    var x : string ="value";
    module Bar
    {
        export var x = x;
    }
}

It compiles to the following JavaScript:

它编译为以下 JavaScript:

var Foo;
(function (Foo) {
    var x = "value";
    var Bar;
    (function (Bar) {
        Bar.x = Bar.x;
    })(Bar || (Bar = {}));

})(Foo || (Foo = {}));

The problem is the line that says Bar.x = Bar.x. How can I set Bar.x to Foo.x? Is it required to exportFoo.xso I can say Bar.x = Foo.x?

问题是说Bar.x = Bar.x. 如何将 Bar.x 设置为 Foo.x?需要exportFoo.x这样我才能说Bar.x = Foo.x吗?

回答by Fenton

It is definitely possible if you remove the ambiguity in the naming:

如果您消除命名中的歧义,绝对有可能:

module Foo
{
    var a : string = "My Value";
    export module Bar
    {
        export var x = a;
    }
}

alert(Foo.Bar.x);