2009-11-05 24 views
0

我要關閉我的窗口(只是一個絕對位置可拖動DIV)當我點擊的緊密聯繫OOP與回調

於JavaScript這是我的代碼

function ApplicationWindow() { 
    this.window = $('<div class="window"></div>'); 

    this.create = function create() { 
     //..... 
     var closeButton = this.window.find('.close'); 
     closeButton.live('click', this.close); 
    } 

    this.close = function close() { 
     this.window.fadeOut(200); 
    }; 
} 

當我點擊在關閉按鈕上執行關閉功能,但問題是我得到一個錯誤「this.window is undefined」。這是因爲關閉函數是作爲回調傳遞的,但我的問題是我如何能夠很好地解決這個問題?

回答

0

這樣;

function ApplicationWindow() { 
    this.window = $('<div class="window"></div>'); 

    this.create = function create() { 
     //..... 
     var closeButton = this.window.find('.close'); 
     var self = this; 
     closeButton.live('click', function() { 
      self.window.fadeOut(200); 
     }); 
    } 
} 
1

請勿使用this。在JS中,保留字this根據上下文而變化,所以在這種情況下您要避免它。

使用範圍一個簡單的變量應該解決的問題:

function ApplicationWindow() { 
    var theWindow = $('<div class="window"></div>'); 

    this.create = function create() { 
     //..... 
     var closeButton = theWindow.find('.close'); 
     closeButton.live('click', this.close); 
    } 

    this.close = function close() { 
     theWindow.fadeOut(200); 
    }; 
} 
+0

使用全局環境將函數綁定到變量不一定是一個乾淨的解決方案,但它會起作用。 – 2009-11-05 16:18:21

+0

@Yuval:那不是全局的,它只是在ApplicationWindow函數的範圍內... – Seb 2009-11-05 16:22:00

+0

@Yuval:如果你用'var'聲明變量,那麼你只將範圍設置爲當前函數。如果你不這樣做,那麼是的,全局範圍被用來代替。 – Seb 2009-11-05 16:22:54

0

什麼庫您使用?你應該能夠在功能綁定到你的對象:

this.close = function close() { 
    this.window.fadeOut(200); 
}.bind(this); 
+0

我正在使用的庫是jQuery – Derk 2009-11-05 16:25:49

0

對JavaScript的好奇this - 結合功能的說明,以及如何解決它使用一個明確的關閉或function.bindthis answer