YonatanAr
YonatanAr

Reputation: 164

setting timeout function within an object

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.

Upvotes: 2

Views: 370

Answers (2)

jacksbox
jacksbox

Reputation: 919

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;
}

Upvotes: 0

Buzinas
Buzinas

Reputation: 11725

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

Upvotes: 2

Related Questions