Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - Trigger one prototype function from another (including itself)

The Problem

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.

However, I'd like my update function to be able to call both itself and then call render.

My Code

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

What I have also Tried

requestAnimationFrame(render);
requestAnimationFrame(update);

And..

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

And...

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

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.

This is the error I receive;

Game.js:6 Uncaught TypeError: Failed to execute 'requestAnimationFrame' on 'Window': The callback provided as parameter 1 is not a function.

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 multiple prototype functions - how to call one from another

calling function from prototype function

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Those lines

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

should be

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...