在 javascript 函数对象中使用时,我遇到了有关 javascript“this”关键字的问题。我希望能够创建一个对象来处理模态弹出窗口(JQuery UI 对话框)。
该对象称为 CreateItemModal。我希望能够实例化并传递一些配置设置。配置设置之一。当调用 show 方法时,将显示对话框,但取消按钮不起作用,因为 this 引用的是 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');
};
最佳答案
您需要创建一个闭包来捕获 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);
}
});
};
关于Javascript 函数对象,this 关键字指向错误的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2490893/