JavaScript - Owner of "this"
Solution 1:
If you want to have the this
property be consistent, you should bind the functions that are being called.
For example,
setInterval(function() { /* code here */ }.bind(this), 500)
That way, the this
of the inner function will be the same as that of the outer function.
Solution 2:
Whenever you see function
you can assume the value of this
changes, so inside the callback function for the interval this
is actually the window
, not the object.
The easy solution is to just store this
in a variable
function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
function getTime(){
var day = new Date();
return day.getTime();
}
this.start = function(){
var self = this;
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(self.duration());
},500);
}
this.duration = function(){
return (time1 - time2) / 1000;
}
}