Javascript函数对象,此关键字指向错误的对象 [英] Javascript function objects, this keyword points to wrong object

查看:66
本文介绍了Javascript函数对象,此关键字指向错误的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript功能对象中使用javascript"this"关键字时,我遇到了问题.我希望能够创建一个用于处理Modal弹出窗口(JQuery UI对话框)的对象.

I've got a problem concerning the javascript "this" keyword when used within a javascript functional object. I want to be able to create an object for handling a Modal popup (JQuery UI Dialog).

该对象称为CreateItemModal.我希望能够实例化并通过一些配置设置.配置设置之一.调用show方法时,将显示对话框,但是取消"按钮不起作用,因为该按钮指向DOM对象而不是CreateItemModal对象.

The object is called CreateItemModal. Which i want to be able to instantiate and pass some config settings. One of the config settings. When the show method is called, the dialog will be shown, but the cancel button is not functioning because the this refers to the DOM object instead of the CreateItemModal object.

如何解决此问题,或者有更好的方法将单独的行为放在单独的类"或对象"中.我已经尝试了几种方法,包括将"this"对象传递到事件中,但这似乎不是一个干净的解决方案.

How can I fix this, or is there a better approach to put seperate behaviour in seperate "classes" or "objects". I've tried several approaches, including passing the "this" object into the events, but this does not feel like a clean solution.

请参见下面的(简化)代码:

See (simplified) code below:

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上下文,我倾向于使用匿名函数来执行以下操作:-

You need to create a closure to trap the this context, I tend to use an anonymous function to do this as follows:-

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函数对象,此关键字指向错误的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆