0

次のようにラッパー、モックサンプルを作成しています

var car = function() { 
}

car.prototype.method1 =  function() {
    this.method2();
}

car.protoptype.method2 = function(callback) {
   var request =  foo() //call to async method

   request.onsucces  = function() {
       this.method3();
   });
}

car.protoptype.method3 = function(callback) {
    this.method4(); //not found
}

car.protoptype.method4 = function(callback) {
     //code
}

//呼び出し元

var vehicle = new Car;
vehicle.method1()

私の問題は、メソッド 4 が呼び出されないことです。onsuccess コールバックにネストされているため、「this」はメソッド 4 のオブジェクトに適用されませんか?

4

3 に答える 3

2

欲しくなると思いますfn.bind

request.onsuccess = this.method3.bind(this);

var that = this;このようにして、コンテキストハッキングを回避できます

これは ECMAScript 5 に依存しており、恐竜ブラウザーでは機能しないことに注意してください。有史以前のソフトウェアをサポートする必要がある場合は、es5-shimを調べてください。

于 2013-09-07T17:41:01.287 に答える
1

これはおそらくcontext、コールバック内の from が原因です。this次のように参照を保存できますself

car.protoptype.method2 = function(callback) {
   var self = this;
   var request =  foo() //call to async method

   request.onsucces(function() {
       self.method3()
   });
}

を使用することを他の人が提案していますFunction.prototype.bind。このアプローチの問題点は、古いブラウザー (<= IE8) では機能しないことです。必要に応じて、この動作をいつでもポリフィルできます。

于 2013-09-07T17:40:02.143 に答える
1

使用するFunction.prototype.bind()

request.onsuccess = this.method3.bind(this);

これにより、値としてバインドされた最初の引数として渡した値を持つ新しい関数が作成されthisます。

于 2013-09-07T17:40:53.357 に答える