简体   繁体   中英

How to call this.function within setTimeout in JS?

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?

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);
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM