2017-02-03 6 views
-2

こんにちは、私はes6と特にクラスのメソッドで問題があります。私exempleを参照してください。コールajaxの後にjavascriptメソッドでコンテキストを保持するには?

私の最初のクラス:

class A{ 
    constructor(){ 
     this.B = new B(); 
     this.test = 5; 
    } 
    methodA1(){ 
     B.methodB1(this.methodA2); 
    } 
    methodA2(){ 
     console.log(this.test); 
    } 
} 

番目のクラス:あなたはmethodA1、コードのリターンを実行すると

class B{ 
    methodB1(callback){ 
     $.get("url",function(data){ 
       ... 
       callback(); 
     }); 
    } 
} 

:これは(methodeA2に)定義されていません! 実際、ajax呼び出しでコールバック関数を呼び出すと、コールバックはクラスのコンテキストを失いました。誰かがこの問題を克服する考えを持っていますか?

ありがとうございました。

+0

これは、非同期操作の性質です。約束を見てください。 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) –

答えて

3

.bindを使用してthisをバインドすることができます。

methodA1(){ 
    this.B.methodB1(this.methodA2.bind(this)); 
} 
+3

正解ですが、オリジナルコードの間違いを修正しません: 'this.B.methodB1(this.methodA2 .bind(this)); ' –

+0

私は編集しました、ありがとう! –

1

あなたは正しく、あなたのコンストラクタで作成しBプロパティを参照していないので、あなたは、エラーが発生します。

クラスAのコンテキストでmethodA1を呼び出すことが確実であれば、プロパティBthis.Bで参照できます。 this conextはBが存在するクラスAの基準を指し示すことになる。

class A{ 
    constructor(){ 
     this.B = new B(); 
     this.test = 5; 
     this.methodA2 = this.methodA2.bind(this); 
     // I prefer to bind my methods in the constructor so they are bound once 
    } 
    methodA1(){ 
     this.B.methodB1(this.methodA2); 
// ^-- the B property created in constructor B exists as a property 
//   of this class, to reference it within a class method you need 
//   to call this.B 
    } 
    methodA2(){ 
     console.log(this.test); 
    } 
} 

class B{ 
    methodB1(callback){ 
     $.get("url",function(data){ 
       ... 
       callback(); 
     }); 
    } 
} 

const a = new A(); 
a.methodA1(); // will log out 5 when the `$.get` request has its callback invoked 
関連する問題