Javascript function objects, this keyword points to wrong object

风流意气都作罢 提交于 2019-12-04 04:11:32

问题


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).

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.

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');
};

回答1:


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);
        }
    });
};



回答2:


Everyone who encounters problems with "this" in JavaScript should read and digest this blog post: http://howtonode.org/what-is-this

You would also do well to Google "Douglas Crockford" and watch some of his (free) videos on the subject.




回答3:


try this:

CreateItemModal.prototype.show = function() {
    var me = this;
    this.$wrapper.dialog({
        buttons: {
            // this crashes because this is not the current object here
            Cancel: me.close
        }
    });
};

The reason why it doesn't work, because the "this" is referring to the dialog, not to that class.




回答4:


Try to add a variable that is equal to global this e.g

function CreateItemModal(config) {
    // initialize some variables including $wrapper
};

CreateItemModal.prototype.show = function() {
    var $this = this;
    this.$wrapper.dialog({
    buttons: {
        // this crashes because this is not the current object here
        Cancel: $this.close
    }
});

As for me, it works in most cases



来源:https://stackoverflow.com/questions/2490893/javascript-function-objects-this-keyword-points-to-wrong-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!