0

I am creating a wrapper, mock sample as follows

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
}

//caller

var vehicle = new Car;
vehicle.method1()

My issue is that method 4 isn't called. As its nested in the onsuccess callback, would the 'this' not scope to the object in method 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来自回调内部。您可以将引用存储thisself

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 回答