从回调中调用原型方法

Calling prototype methods from within callback

本文关键字:原型 方法 调用 回调      更新时间:2023-09-26

我正在创建一个包装器,模拟示例如下

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

我想你会想要fn.bind

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

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

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

使用 Function.prototype.bind()

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

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

这可能是由于回调中的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)中不起作用。 如果您愿意,始终可以填充此行为。