1

I'm a little bit new to javascript and I came across this error while writing a game. It stumps me since this function seems the same as all of the other functions, yet, it doesn't work.

function Game() {}
Game.prototype.loadGame = function(x) {
  this.cvs=document.getElementById(x);
  this.cvs.height=480;
  this.cvs.width=640;
  this.sprites=[];
  this.ctx=cvs.getContext("2d");
};
Game.prototype.update = function() {
  console.log("u");
};
Game.prototype.draw = function() {
  this.drawCircle(320, 240, 10, "green")
};
Game.prototype.drawCircle = function(centerX, centerY, radius, color) {
  this.ctx.beginPath();
  this.ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  this.ctx.fillStyle = color;
  this.ctx.fill();
};
Game.prototype.tick = function() {
  this.update();
  this.draw();
};
Game.prototype.Init = function() {
  fps=60
  this.loadGame("cvs");
  setInterval(this.tick, (1/fps)*1000);
};
g = new Game();
g.Init();

I get the error: Uncaught TypeError: Object [object global] has no method 'update'

Any idea as to how to fix this?

1
  • In the future, when asking questions, I highly recommend providing some context as to what your code is supposed to do. Commented Aug 4, 2013 at 0:57

2 Answers 2

2

It's because you're using setInterval(), so your tick function isn't getting the 'this' that you expect. You need to do this instead:

Game.prototype.Init = function() {
    var that = this;
    fps=60
    this.loadGame("cvs");
    setInterval(function() { that.tick.call(that); }, 1);
}

Google for "javascript this" or "javascript call" or "javascript apply" to get more info.

Sign up to request clarification or add additional context in comments.

3 Comments

call is not required here, that.tick() would be enough.
@bfavaretto Thanks, I didn't realize that. I learned something about this/that just now.
I'm glad to hear that, and I know this can be really tricky!
1

In JavaScript, the value of this is dynamic, and depends on how the function is called. Since you're using the canvas, we can assume bind is available, so this should work:

setInterval(this.tick.bind(this), (1/fps)*1000);

Note: you might also want to use requestAnimationFrame for a better frame rate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.