2011-05-03 19 views
5

我有以下JS:如何在JS的setTimeout中調用this.function?

function TrackTime() { 

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

} 

我有一個閉合(如上所示)嘗試這樣做,也是十幾其他方式。我似乎無法讓這個工作在任何瀏覽器。 setTimeout函數在沒有在「類」函數中調用時工作正常。有人可以幫助我嗎?

回答

9

這是因爲在「此」執行功能時的範圍發生變化的。

試一下,這一招..

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

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

謝謝,像一個魅力工作。 – Josh 2011-05-03 21:14:29

0

你可以試試這個:

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

的原因,你不能使用這裏封閉是因爲setTimeout的逃跑窗口對象,所以「這個」永遠是「窗口」。您需要在這裏使用部分函數應用程序來設置函數的上下文(以及可選的某些預定義參數!),而將保留爲參考,因此它可以用作事件處理程序!整潔呃?見下文。

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