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

标签 javascript jquery this

在 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/

相关文章:

javascript - 对此,全局对象和全局范围的混淆

javascript - 使用PHP、MSSQL、Jquery进行即时搜索

javascript - 使用 php 或 javascript 过滤结果

javascript - Accordion 标题子项的停止单击、Enter 和箭头键

jquery - 使用 jQuery : should I use $. ajaxSetup() 或 $.fn.ajaxError() 处理 AJAX 错误

javascript - 'this' 上下文在赋值过程中丢失,但也不完全丢失?

javascript - 改变子组件的状态

javascript - 常见问题 - Accordion 展开/折叠功能

Javascript:第一个下拉框有效,但另一个无效。代码是一样的

javascript - 获取函数调用者作用域