How to call requestAnimFrame on an object method?

2019-06-14 07:43发布

Say I have the following object:

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;
}

This does not work. FireFox gives me an error:

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

I would like to know why, and what other solution could be used instead to call an object's update method without calling it from your main function(i.e. while keeping the object anonymous).

1条回答
聊天终结者
2楼-- · 2019-06-14 08:37

requestAnimationFrame doesn’t bind this to anything, like any direct call. You can do that manually using Function.prototype.bind:

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

Binding permanently is another way:

function Foo() {
    …
    this.update = this.update.bind(this);
    this.update();
}
查看更多
登录 后发表回答