2010-11-01 69 views
8

我有這樣的類/函數如何從方法的函數內訪問原型的父這個

function Menu() 
{ 
    this.closetimer = 0; 
    this.dropdown = 0; 
} 

Menu.prototype.menuTimer = function() 
{ 
    this.closetimer = setTimeout(function() 
    { 
    this.menuClose(); 
    }, this.timeout); 
} 

Menu.prototype.menuClose = function() 
{ 
    if(this.dropdown) this.dropdown.css('visibility','hidden'); 
} 

我要調用的函數menuClose()這是Menu類的一部分,但我覺得這個代碼實際上是嘗試從closetimer對象中調用menuClose()

如何從menuTimer()的Menu對象中引用menuClose()

回答

15

在你setTimeout()回調,thiswindow,只要保持這樣的引用:

Menu.prototype.menuTimer = function(){ 
    var self = this; 
    this.closetimer = setTimeout(function(){ 
     self.menuClose(); 
    }, this.timeout); 
} 
+0

衛生署!謝謝!腦屁。 – polyhedron 2010-11-01 20:35:15

+0

@ polyhedron - welcome :) – 2010-11-01 20:36:10

4

您定義的菜單(本),同時您可以訪問它的引用..

Menu.prototype.menuTimer = function(){ 
    var _self = this; 
    this.closetimer = setTimeout(function(){ 
     _self.menuClose(); 
    }, this.timeout); 
} 
+0

您應該使用'var _self'來防止與全局名稱空間的衝突。 – MForster 2010-11-01 20:29:24

+0

@MFoster,已經更正,謝謝:)觸發快樂.. – 2010-11-01 20:30:32

6

另一種方法是綁定內部函數。

Menu.prototype.menuTimer = function(){ 
this.closetimer = setTimeout(function(){ 
    this.menuClose(); 
}.bind(this), this.timeout); 
} 

Menu.prototype.menuTimer = function(){ 
this.closetimer = setTimeout(this.menuClose.bind(this), this.timeout); 
} 
+1

這可以寫成'setTimeout(this.menuClose.bind(this),this.timeout)'? – MForster 2010-11-01 21:40:27

+0

你是絕對正確的,我已經更新它來顯示。這是迄今爲止最好的解決方案。給我所有的選票! – clockworkgeek 2010-11-01 21:52:16

+0

這確實讓你聽起來有點貪婪:-) – MForster 2010-11-01 21:56:19

相關問題