我正在創建一個Javascript模塊,其任務基本上是通過點擊一個按鈕動態生成一個通過Ajax打開的模式。這個按鈕有一個數據屬性,我傳遞給Ajax調用來告訴它我想打開哪個模式。This Keywords * within * Javascript Module
這裏是模塊的簡化版本:
(function() {
let modalwindow = {
init: function() {
this.bindEvents();
},
bindEvents: function() {
$(document).on('click', '[data-action="open-modal"]', this.ajaxCall.bind(this));
},
ajaxCall: function() {
$.ajax({
url: ajax.url,
type: 'post',
context: this,
data: {
modal_id: this.modalID, // In this case, I need *this* to refer to the button
action: 'open_modal'
},
success: function (response) {
// In this case, I need *this* to refer to the modalwindow object
this.openModal(response, this.modalID);
}
});
},
openModal: function(response, modalID) {
$(response).appendTo(Body).attr('data-state', 'active-modal');
}
}
modalwindow.init();
})()
問題是,在ajaxCall
方法我需要的這關鍵字指的是兩個不同的東西:我需要它來指按鈕時我設置了modal_id參數;我需要它引用模態窗口對象來調用成功的openModal
方法。我怎麼做?
現在這個總是指模態窗口對象,其實openModal
的作品;但modal_id參數是錯誤的,因爲在那裏這個應該參考按鈕。
我對Modular JS非常陌生,這一直讓我瘋狂。我發現了類似的問題,但似乎沒有解決模塊中所有方法的問題。
[JavaScript關閉如何工作?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Salketer
*「This Keyword * within * Javascript Module」* The單詞「模塊」現在在JavaScript中具有[特定的技術含義](https://tc39.github.io/ecma262/#sec-modules)(而在ES2015之前,它沒有,並且鬆散地用來指任何解決問題的不同方式的數量)。所以當我沒有提到實際的JavaScript模塊時,我會遠離它。 –