从回调中调用原型方法
Calling prototype methods from within callback
我正在创建一个包装器,模拟示例如下
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)中不起作用。 如果您愿意,始终可以填充此行为。
相关文章:
- 使用“;这个“;JavaScript原型方法中的关键字
- 引用类变量中的原型方法
- 如何从对象的原型方法访问JavaScript对象属性
- 如何从构造函数中调用js原型方法
- Javascript不调用原型方法
- 有没有任何情况下,一个方法不应该是原型方法
- 调用影子原型方法的更简单/更好的方法
- 当对象从服务器发送到客户端时,JS原型方法消失了
- 构造 JavaScript Array 原型方法
- 在Javascript中扩展继承的原型方法
- 如何在另一个原型中创建可调用的原型方法
- 覆盖原型方法
- 实现原型方法
- 从原型方法更改实例属性
- XrayWrapper 错误(值是可调用的)在 Firefox 插件中覆盖原型方法时
- 避免在外部称为原型方法中丢失对象实例
- 原型方法不是一个函数,为什么
- 是否可以从 javascript 中的原型方法访问私有类属性
- 找不到 Javascript 原型方法覆盖
- 调用本机原型方法时扩展或继承对象原型