繁体   English   中英

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

[英]How to call this.function within setTimeout in JS?

我有以下JS:

function TrackTime() {

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

}

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

这是因为执行 function 时“this”的 scope 发生了变化。

试试这个技巧..

    function TrackTime() {  
        this.CountBack = function(secs) {         
            var that = this;

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

你可以试试这个:

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

您无法在此处使用闭包的原因是因为 setTimeout 超出了 window object,因此“this”始终是“window”。 您需要在此处使用部分 function 应用程序来设置 function 的上下文(以及可选的一些预定义参数!),同时将其保留为参考,因此它可以用作事件处理程序吗? 整齐嗯。 见下文。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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