Skip to content Skip to sidebar Skip to footer

Javascript Function Objects, This Keyword Points To Wrong Object

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 (JQuer

Solution 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 hereCancel: (function(self) {
              returnfunction() { self.close.apply(self, arguments ); }
            })(this);
        }
    });
};

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

Solution 3:

try this:

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

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

Solution 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

Post a Comment for "Javascript Function Objects, This Keyword Points To Wrong Object"