I have the following JS:
function TrackTime() {
this.CountBack = function(secs) {
setTimeout(function(){this.CountBack(secs)}, SetTimeOutPeriod);
}
}
I have tried this with a closure (seen above) and also about a dozen other ways. I can't seem to get this to work in any browser. The setTimeout function works fine when not being called in a "class" function. Can someone please help me with this?
I have the following JS:
function TrackTime() {
this.CountBack = function(secs) {
setTimeout(function(){this.CountBack(secs)}, SetTimeOutPeriod);
}
}
I have tried this with a closure (seen above) and also about a dozen other ways. I can't seem to get this to work in any browser. The setTimeout function works fine when not being called in a "class" function. Can someone please help me with this?
Share Improve this question asked May 3, 2011 at 20:37 JoshJosh 3,61114 gold badges51 silver badges72 bronze badges3 Answers
Reset to default 9This happens because of the change in the scope of "this" when the function is executed.
Try that-this trick..
function TrackTime() {
this.CountBack = function(secs) {
var that = this;
setTimeout(function(){that.CountBack(secs)}, SetTimeOutPeriod);
};
}
You could try this:
var that = this;
this.CountBack = function (secs) {
setTimeout(function () {that.CountBack(secs)}, SetTimeOutPeriod);
}
The reason your not able to use closures here is because setTimeout runs off the window object, so 'this' is always 'window'. You'll want to use a partial function application here to set the context (and optionally some predefined parameters!) of your function while keeping it as a reference, so it can be used as event handler! Neat eh? See below.
// This will call a function using a reference with predefined arguments.
function partial(func, context /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(context ? context : this, allArguments);
};
}