从回调内调用原型方法

时间:2013-09-07 17:37:27

标签: javascript

我正在创建一个包装器,模拟样本如下

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中对象的范围吗?

3 个答案:

答案 0 :(得分:2)

我想你会想要fn.bind

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

这样您可以避免任何var that = this;上下文黑客攻击

注意这依赖于ECMAScript 5,并且无法在恐龙浏览器中使用。如果您需要支持史前软件,请查看es5-shim

答案 1 :(得分:1)

这可能是由于回调中的context造成的。您可以将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)。如果您愿意,可以随时polyfill this behavior

答案 2 :(得分:1)

使用Function.prototype.bind()

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

这将创建一个新函数,其值作为第一个参数绑定为this值。