假设我有以下对象:
function Foo(value){
this.bar = value;
this.update();
}
Foo.prototype.update = function(){
console.log(this.bar);
this.bar++;
requestAnimationFrame(this.update);
}
Foo.prototype.setBar(value){
this.bar = value;
}
这不起作用。 FireFox 给我一个错误:
NS_ERROR_ILLEGAL_VALUE: Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIDOMWindow.requestAnimationFrame]
我想知道为什么,以及可以使用什么其他解决方案来调用对象的更新方法,而不从主函数中调用它(即保持对象匿名)。
最佳答案
requestAnimationFrame
不会将 this
绑定(bind)到任何东西,就像任何直接调用一样。您可以使用 Function.prototype.bind
手动执行此操作:
Foo.prototype.update = function(){
console.log(this.bar);
this.bar++;
requestAnimationFrame(Foo.prototype.update.bind(this));
};
永久绑定(bind)是另一种方式:
function Foo() {
…
this.update = this.update.bind(this);
this.update();
}
关于javascript - 如何在对象方法上调用requestAnimFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177297/