开发者

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 = {

    myC开发者_高级运维ustomValue: 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜