簡體   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