我正在创建一个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模块时,我会远离它。 –