打字稿:如何访问"以上两级"属性

Out*_*ger 3 javascript typescript

快速提问 - 如何访问"以上两级"属性?TypeScript中的测试示例:

export class Test {
    testVariable: string;
    constructor() { }

    TestFunction() {
        MyFunctions.Proxy.Join() { //some made up function from other module
            //HERE
            //How can I here access testVariable property of Test class?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者甚至可以在TypeScript(或一般的JavaScript)中访问这样的属性?

编辑+回答:由于我的问题不够明确,我带来了一些关于这个问题的新信息.通过启动程序员这是一个非常常见的问题.

这里的问题是this改变它的上下文 - 首先它指的是类Test,然后它指的是我的内部函数 - Join().为了实现正确性,我们必须使用lambda表达式进行内部函数调用或使用一些替换值this.

第一个解决方案是接受的答案.

其次是:

export class Test {
    testVariable: string;
    constructor() { }

    TestFunction() {
        var myClassTest: Test = this;
        MyFunctions.Proxy.Join() { //some made up function from other module
            myClassTest.testVariable; //approaching my class propery in inner function through substitute variable
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 5

如果您使用fat-arrow语法,它将保留您的词法范围:

export class Test {
    testVariable: string;
    constructor() { }

    TestFunction() {
        var MyFunctions = {
            Proxy: {
                Join: function() {}
            }
        };

        MyFunctions.Proxy.Join = () => {
            alert(this.testVariable);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)