如何在对象方法上调用requestAnimFrame? [英] How to call requestAnimFrame on an object method?

查看:135
本文介绍了如何在对象方法上调用requestAnimFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下对象:

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).

推荐答案

requestAnimationFrame 不会将绑定到任何内容,就像任何直接调用一样。你可以使用 Function.prototype.bind

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

这篇关于如何在对象方法上调用requestAnimFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆