Javascript 如何在对象方法上调用requestAnimFrame?
假设我有以下目标:Javascript 如何在对象方法上调用requestAnimFrame?,javascript,oop,requestanimationframe,Javascript,Oop,Requestanimationframe,假设我有以下目标: 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; } 这是
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
与任何直接调用一样,不会将此绑定到任何对象。您可以使用以下方法手动执行此操作:
永久绑定是另一种方式:
function Foo() {
…
this.update = this.update.bind(this);
this.update();
}
@对。手动执行
var=this;requestAnimationFrame(函数(){that.update();})代码>。
function Foo() {
…
this.update = this.update.bind(this);
this.update();
}