最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call this.function within setTimeout in JS? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 9

This 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);
  };
}
发布评论

评论列表(0)

  1. 暂无评论