如何在对象方法上调用requestAnimFrame?

时间:2013-11-24 17:04:58

标签: 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;
}

这不起作用。 FireFox给了我一个错误:

NS_ERROR_ILLEGAL_VALUE: Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIDOMWindow.requestAnimationFrame]

我想知道为什么,以及可以使用什么其他解决方案来调用对象的更新方法而不从主函数调用它(即保持对象匿名)。

1 个答案:

答案 0 :(得分:2)

requestAnimationFrame不会将this绑定到任何内容,就像任何直接调用一样。您可以使用Function.prototype.bind手动执行此操作:

Foo.prototype.update = function(){
    console.log(this.bar);
    this.bar++;
    requestAnimationFrame(Foo.prototype.update.bind(this));
};

永久绑定是另一种方式:

function Foo() {
    …
    this.update = this.update.bind(this);
    this.update();
}
相关问题