Maxim Gershkovich
Maxim Gershkovich

Reputation: 47149

jQuery 'this' keyword in custom methods

In lots of cases I have seen the greatness of how jQuery modifies the this keyword to give the object that you would expect to be there actually be there. Great....

However how do you deal with situation where you have custom objects that have custom methods which reference the this keyword but are called thru jQuery.

For example:

var myCustomObject = {

    myCustomValue: 1,

    myCustomMethod: function () {
        switch (this.myCustomValue) {
            case ....
        }
    }

};

If called using a jQuery callback "this" is now the jQuery "context" and obviously returns undefined for myCustomValue.

I have noticed that I can refer to the instance directly such as

switch (myCustomObject.myCustomValue) {}

But this seems annoyingly verbose and I wonder if any unexpected side affects could be caused by this...

What is best practice for such scenarios?

Upvotes: 0

Views: 116

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

If it doesn't have to be public:

var myCustomObject = new (function()
{
    var myCustomValue = 1;
    this.myCustomMethod = function () {
        switch (myCustomValue) {

        }
    }
})();

If it does:

var myCustomObject = new (function()
{
    this.myCustomValue = 1;
    var self = this;
    this.myCustomMethod = function () {
        switch (self.myCustomValue) {

        }
    }
})();

self can be called whatever you want.

Upvotes: 6

icktoofay
icktoofay

Reputation: 128991

You could keep the same syntax if you had a function like this:

function patchThis(obj) {
    function patchFunction(orig) {
        return function() {
            return orig.apply(obj, arguments);
        };
    }
    for(var i in obj) {
        if(obj.hasOwnProperty(i)&&typeof obj[i]=="function") {
            obj[i]=patchFunction(obj[i]);
        }
    }
}

Then just call patchThis on myCustomObject.

You can see an example here.

Upvotes: 2

Related Questions