2

I'm creating a game with one hero figure that his mission is to collect fruits all over the canvas.

the thing is that each fruit has it's own expiration time on the canvas. For example, banana will appear 5 seconds, orange will appear 10 sec etc..

the thing im trying to do, is to create an object that each instance of this object has a timer that change a boolean value after selected time

my code looks like this :

function apple(timeToStay,score){
this.kind = "apple";
this.timeTostay = timeToStay;
this.score=score;
this.imgsrc =  "images/apple.png";
this.x = 32 + (Math.random() * (canvas.width - 64));
this.y = 32 + (Math.random() * (canvas.height - 64));
this.removeMe = false;

setTimeout(function() { this.removeMe=true; }, timeToStay*1000);

return this;

}

as you can see i thought that setting a timeout with the instance will fire this after 5 seconds for example if i created it var obj = apple(5,5)

at the beginning obj.removeMe should be false but after 5 seconds it should turn into true.

1
  • 2
    this is function scoped. So it changes inside the timeout function. Use var _this = this in the constructor, and _this in the timeout. Commented Oct 4, 2015 at 15:13

2 Answers 2

2

This is happening because the function you're passing as parameter to the setTimeout method doesn't keep the same context, because of the Javascript's lexical scoping.

You can override that behavior by using Function.prototype.bind, e.g:

setTimeout(function() { this.removeMe=true; }.bind(this), timeToStay*1000);
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

function apple(timeToStay,score){
  this.kind = "apple";
  this.timeTostay = timeToStay;
  this.score=score;
  this.imgsrc =  "images/apple.png";
  this.x = 32 + (Math.random() * (canvas.width - 64));
  this.y = 32 + (Math.random() * (canvas.height - 64));
  this.removeMe = false;

  var base = this;

  setTimeout(function() { base.removeMe=true; }, timeToStay*1000);

  return this;
}

1 Comment

This is very bad practive, you should always use the bind/call/apply for this kind of issues.

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.