触发一个原型函数

触发一个原型函数

本文介绍了从另一个(包括它自己)触发一个原型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a constructor called Game. Then, I tried to expand it's functionality by adding two new functions (update and render) using prototype.

但是,我希望我的 update 函数能够调用 自身,然后调用 render.

However, I'd like my update function to be able to call both itself and then call 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 - 我猜这是因为函数是如何创建的.

But due to some (glaringly obvious) gaps in my javascript knowledge, I can't make this work. It appears as if this and parent are both referring to window - I'm guessing that's because of how the functions were created.

这是我收到的错误;

Game.js:6 Uncaught TypeError: Failed to executeWindow"上的requestAnimationFrame":回调提供为参数 1 不是函数.

我已经找到的问题

我已经在 SO 上找到了以下问题,但它们似乎对这个特定问题没有太大帮助.

Questions I've already found

I've already found the following questions on SO, but they don't appear to be all that helpful to this particular problem.

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

从原型函数调用函数

推荐答案

那些行

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

应该

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

否则,在递归的第二次执行中,关键字this 将引用window 对象而不是Game.并且 window.update 显然不是函数,正如错误指定的那样.

Otherwise, in the second execution of your recursion, keyword this will refer to window object instead of Game. And window.update is obviously not a function, as the error specified.

这篇关于从另一个(包括它自己)触发一个原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:24