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

标签 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]

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

最佳答案

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/

相关文章:

javascript - .js 和无尽的旋转器

c++ - 使用不受支持的类方法时抛出编译器错误

Java OOP 三角形的存在性

oop - 包含首字母缩写词的类的命名约定

javascript - 如果可能的话,我真的不应该使用 setInterval 和 setTimeout 吗?

javascript - requestAnimationFrame 没有触发提供给它的函数

javascript - 等待 Canvas 动画并获取完成

javascript - 启动 Node 服务器,每天在特定时间加载页面

javascript - Chrome 控制台和扩展程序之间的结果不同

javascript - VueJS 2 v-for表单输入单选按钮检查属性不起作用