3

簡単な質問 - 「2 レベル上」のプロパティにアクセスするにはどうすればよいですか? 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?
        }
    }
}

それとも、TypeScript (または JavaScript 一般) でそのようなプロパティにアクセスすることさえ可能ですか?

編集 + 回答:私の質問が十分に明確ではなかったため、この問題に関する新しい情報をいくつか提供します。プログラマー初心者からよく聞かれる質問です。

ここでの問題は、thisそのコンテキストを変更することです-最初にクラスTestを参照し、次に内部関数を参照します- Join(). 正確さを達成するには、内部関数呼び出しにラムダ式を使用するか、 の代替値を使用する必要がありますthis

最初の解決策は、受け入れられた回答にあります。

2番目はこれです:

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
        }
    }
}
4

1 に答える 1

5

ファット アロー構文を使用すると、レキシカル スコープが維持されます。

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

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

        MyFunctions.Proxy.Join = () => {
            alert(this.testVariable);
        }
    }
}
于 2013-11-14T16:58:10.937 に答える