The value of this
is NOT preserved in your setInterval()
callback. You have to save that value you want to another variable before the setInterval()
call and use that inside the setInterval()
.
this.growImage = function() {
console.log("growImage:" + this.dom.id + "counter:" + this.grow_counter);
if(this.grow_counter == 0) {
var self = this;
this.tim_grow = window.setInterval(
/******* FUNCTION TO BE CALLED BY SETINTERVAL ********/
function() {
self.grow_counter++;
console.log("self.growStepByStep(): self.grow_counter = " + this.grow_counter); /*this is displayed as NaN */
if(self.grow_counter > this.times) {
window.clearInterval(self.tim_grow);
self.grow_counter = 0;
}
}
/******* FUNCTION TO BE CALLED BY SETINTERVAL ********/
,
20);
}
}
Or, if you are using modern browsers only, you can also use .bind()
to manipulate the value of this
to be set as you want like this:
this.growImage = function() {
function intervalCallback() {
this.grow_counter++;
console.log("this.growStepByStep(): this.grow_counter = " + this.grow_counter); /*this is displayed as NaN */
if(this.grow_counter > this.times) {
window.clearInterval(this.tim_grow);
this.grow_counter = 0;
}
}
console.log("growImage:" + this.dom.id + "counter:" + this.grow_counter);
if(this.grow_counter == 0) {
this.tim_grow = window.setInterval(intervalCallback.bind(this), 20);
}
}