2010-03-22 68 views
4

我有一個問題,關於在javascript函數對象中使用javascript「this」關鍵字。我希望能夠創建一個對象來處理模式彈出(JQuery UI對話框)。Javascript函數對象,這個關鍵字指向錯誤的對象

該對象稱爲CreateItemModal。我希望能夠實例化並傳遞一些配置設置。其中一個配置設置。當調用show方法時,將顯示對話框,但取消按鈕不起作用,因爲它引用DOM對象而不是CreateItemModal對象。

我該如何解決這個問題,或者是否有更好的方法將單獨的行爲放在單獨的「類」或「對象」中。我嘗試了幾種方法,包括將「this」對象傳入事件中,但這不像是一個乾淨的解決方案。

見(簡體)下面的代碼:

function CreateItemModal(config) { 
    // initialize some variables including $wrapper 
}; 

CreateItemModal.prototype.show = function() { 
    this.$wrapper.dialog({ 
     buttons: { 
      // this crashes because this is not the current object here 
      Cancel: this.close 
     } 
    }); 
}; 

CreateItemModal.prototype.close = function() { 
    this.config.$wrapper.dialog('close'); 
}; 

回答

4

你需要創建一個封閉套住this方面,我傾向於使用匿名函數來做到這一點,如下所示: -

CreateItemModal.prototype.show = function() { 
    this.$wrapper.dialog({ 
     buttons: { 
      // this crashes because this is not the current object here 
      Cancel: (function(self) { 
       return function() { self.close.apply(self, arguments); } 
      })(this); 
     } 
    }); 
}; 
+0

這個工作,但是這是「最佳實踐」?看起來像是一個很大的開銷,讓JavaScript看到這是一個真正的「OO」對象? – 2010-03-22 09:15:56

+0

那麼,那是因爲你使用的是jQuery,而jQuery並不能幫助你編寫那種javascript。對於大多數其他框架,您只需編寫'Cancel:this.close.bind(this)' – Alsciende 2010-03-22 09:20:41

+0

@Rody:這是唯一的做法。 ECMAScript第5版引入了函數原型方法'bind',它可以讓你做這樣的事情:'取消:this.close.bind(this);'。如果你必須在你的代碼中多次執行這樣的事情,那麼在Web上有'bind'原型的實現。 – 2010-03-22 09:22:15

2

試試這個:

CreateItemModal.prototype.show = function() { 
    var me = this; 
    this.$wrapper.dialog({ 
     buttons: { 
      // this crashes because this is not the current object here 
      Cancel: me.close 
     } 
    }); 
}; 

爲什麼它不工作的原因,因爲 「這」 指的是對話,而不是那個班。

+0

很多upvotes上不正確的答案輝煌; P。上面的代碼沒有改變。 close函數仍然在button元素的上下文中執行而不是'CreateItemModal'實例。 – AnthonyWJones 2010-03-22 09:12:17

+0

正確,只是在一分鐘前測試過,而且這不會不幸地工作。 – 2010-03-22 09:16:46

+0

沒錯,因爲'me.close'作爲一個函數存儲在'Cancel'中:它的包含對象'me'丟失了。所以'this'在執行時是'window'。 – Alsciende 2010-03-22 09:19:33

0

嘗試添加一個變量等於全球這個如

function CreateItemModal(config) { 
    // initialize some variables including $wrapper 
}; 

CreateItemModal.prototype.show = function() { 
    var $this = this; 
    this.$wrapper.dialog({ 
    buttons: { 
     // this crashes because this is not the current object here 
     Cancel: $this.close 
    } 
}); 

對我來說,它的工作原理在大多數情況下

3

大家誰遇到問題,「這個」在JavaScript應該閱讀和消化這篇博客文章:http://howtonode.org/what-is-this

你也會對谷歌「道格拉斯克羅克福德」做的很好,並觀看他的一些關於這個主題的(免費)視頻。

相關問題