从另一个(包括其自身)触发一个原型函数

Trigger one prototype function from another (including itself)

本文关键字:一个 原型 函数 包括其 另一个      更新时间:2024-01-11

问题

我创建了一个名为Game的构造函数。然后,我尝试通过使用原型添加两个新功能(updaterender)来扩展它的功能。

但是,我希望我的update函数能够同时调用本身,然后调用render

我的代码

var Game = function(){
};
Game.prototype.update = function(){
    requestAnimationFrame(this.render);
    requestAnimationFrame(this.update);
};
Game.prototype.render = function(){
  console.log('Rendering');
};
var game = new Game();
game.update();

我也尝试过

requestAnimationFrame(render);
requestAnimationFrame(update);

而且。。

requestAnimationFrame(Game.render);
requestAnimationFrame(Game.update);

而且。。。

requestAnimationFrame(Parent.render);
requestAnimationFrame(Parent.update);

但由于我的javascript知识存在一些差距(非常明显),我无法做到这一点。看起来thisparent都指的是window——我猜这是因为函数是如何创建的。

这是我收到的错误;

Game.js:6未捕获类型错误:执行失败"Window"上的"requestAnimationFrame":回调提供为参数1不是函数。

我已经找到的问题

我已经在SO上发现了以下问题,但它们似乎对这个特定的问题没有那么大帮助。

Javascript多个原型函数-如何从另一个调用一个

从原型函数调用函数

那些线

requestAnimationFrame(this.render);
requestAnimationFrame(this.update);

应该是

requestAnimationFrame(this.render.bind(this));
requestAnimationFrame(this.update.bind(this));

否则,在递归的第二次执行中,关键字this将引用window对象,而不是Gamewindow.update显然不是一个函数,正如错误所指出的那样。

您丢失了对Game对象的引用,请尝试像这样绑定"this":

var Game = function(){
};
Game.prototype.update = function(){
    requestAnimationFrame(this.render.bind(this));
    requestAnimationFrame(this.update.bind(this));
};
Game.prototype.render = function(){
  console.log('Rendering');
};
var game = new Game();
game.update();