How to call requestAnimFrame on an object method?

给你一囗甜甜゛ 提交于 2020-01-03 04:45:32

问题


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:


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


来源:https://stackoverflow.com/questions/20177297/how-to-call-requestanimframe-on-an-object-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!