2012-03-23 138 views
0

代碼:在setTimeout(javascript)中處理對象方法函數調用?

​var a = function() { 
    this.message = "hello"; 
    this.shout = function(){ 
     alert(this.message); // alerted undefined 
    } 
    this.Timer = setTimeout(this.shout, 3000); 
} 

var b = new a(); 

我得到的警告對話框中未定義。我已經在setTimeout中嘗試過「this.shout()」,但是在發現留言時出現DOM錯誤。我如何處理這個問題?

回答

0

在功能thisshout指功能shout,而不是功能a

如果你定義在a範圍變量,而不是使用這個,你可以稍後參考它並得到它的值:

var a = function() { 
    var message = "hello"; 
    this.shout = function(){ 
     alert(message); // Alerts hello 
    } 
    this.Timer = setTimeout(this.shout, 3000); 
} 

var b = new a(); 

或者,如果你願意,你可以存儲一個參考,而不是,這樣就可以使用自指a

var a = function() { 
    this.message = "hello"; 
    var self = this; 

    this.shout = function(){ 
     alert(self.message); // Alerts hello 
    } 
    this.Timer = setTimeout(this.shout, 3000); 
} 

var b = new a(); 
0
this.message 

需要位於this.shout函數內,因爲此時它已超出範圍。

然後,它會工作:)

var a = function() { 

    this.shout = function(){ 
     this.message = "hello"; 
     alert(this.message); // alerted undefined 
    } 
    this.Timer = setTimeout(this.shout, 3000); 
} 

var b = new a(); 
0

「這個」內的setTimeout是setTimeout的情況下,你必須在一個VAR外界先前獲得「this」

var a = function() 
{ 
    this.message = "hello"; 
    this.shout = function() 
    { 
     alert(this.message); // alerted undefined 
    } 
    var t = this; 
    this.Timer = window.setTimeout(function() 
    { 
    t.shout(); 
    }, 3000); 
} 

var b = new a();