如何在JS的setTimeout中调用this.function?

5

我有以下JS代码:

function TrackTime() {

    this.CountBack = function(secs) {
        setTimeout(function(){this.CountBack(secs)}, SetTimeOutPeriod);
    }

}

我已经尝试过使用闭包(如上所示)以及其他十几种方法。但似乎在任何浏览器中都无法使其正常工作。当setTimeout函数不在“类”函数中调用时,它可以正常工作。请问有人能帮助我吗?

3个回答

9
这是因为函数执行时"this"的范围发生了改变。
试试这个技巧...
    function TrackTime() {  
        this.CountBack = function(secs) {         
            var that = this;

            setTimeout(function(){that.CountBack(secs)}, SetTimeOutPeriod);     
        };
    } 

0
你可以尝试这个:
var that = this;
this.CountBack = function (secs) {
    setTimeout(function () {that.CountBack(secs)}, SetTimeOutPeriod);
}

0
你无法在这里使用闭包的原因是因为setTimeout是在window对象上运行的,所以'this'始终是'window'。你需要使用部分函数应用程序来设置上下文(和可选的预定义参数!)来保持它作为引用,以便它可以用作事件处理程序!很棒吧?请参见以下内容。
// 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);
  };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接