The nested function doesn't have it's own this
context (it'll simply refer to the window
), so assign a variable to the this
method within shiftImg
to which you can refer in the nested function:
function shiftImg() {
var self = this;
this.offset = 0;
this.shift =
function() {
self.offset++;
console.log("Offset: " + self.offset);
};
}
productImg = new shiftImg();
window.setInterval(productImg.shift, 100);
The reason you need to do this is because the call to setInterval
which invokes the method, is run in a separate execution context, where this
is equal to the window
. If you called this.shift()
from within shiftImg()
you'll see that you it works just fine without the need to add self
. See this MDN article for more.
Alternatively you pass an anonymous function to the callback method in setInterval
:
window.setInterval(function() {
productImg.shift();
}, 100);
If you use objects and jQuery then you'll find into this problem quite a lot, and jQuery's $.proxy
utility method makes doing similar things to above fairly easy.