Javascript函数对象,this关键字指向错误的对象

2023-12-12

在 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);
        }
    });
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript函数对象,this关键字指向错误的对象 的相关文章

随机推荐