Problem:
I have a very simple snippet of code. I create and object with a member variable "counter" and a member function "start()" which increases the counter variable by 1 every second. The problem here is that the counter variable does not increase when start() acts on it. This has been driving my head crazy.
Hypothesis:
I believe this is a problem with the "this" keyword or a scope/closure issue but I'm not sure what's exactly wrong.
Code:
var livePlayer = {
counter : 0,
liveIteration: null,
start: function(){
this.liveIteration = setInterval(this.incCounter, 1000);
},
incCounter: function(){
this.counter++;
alert(this.counter); <-- this should return 0, 1, 2, etc. but returns NAN instead
}
};
livePlayer.start();
JSFiddle:
http://jsfiddle.net/justinwong12337/1wjdr0dh/
Your help is greatly appreciated!
Additional info:
This object and its members are part of an AngularJS service and are to be used by a separate controller file.