自定义方法中的jQuery'the'关键字

时间:2010-11-17 03:54:57

标签: javascript jquery scope this

在很多情况下,我已经看到了jQuery如何修改this关键字以提供您希望实际存在的对象的伟大之处。大....

但是,如何处理自定义对象具有引用此关键字但通过jQuery调用的自定义方法的情况。

例如:

var myCustomObject = {

    myCustomValue: 1,

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

};

如果使用jQuery回调调用“this”现在是jQuery“context”,显然会为myCustomValue返回undefined。

我注意到我可以直接引用实例,例如

switch (myCustomObject.myCustomValue) {}

但这看起来很烦人,我想知道是否有任何意想不到的副作用可能会由此造成......

这种情况的最佳做法是什么?

2 个答案:

答案 0 :(得分:6)

如果不必公开:

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

        }
    }
})();

若是:

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

        }
    }
})();

self可以随意调用。

答案 1 :(得分:2)

如果你有这样的函数,你可以保持相同的语法:

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

然后只需在patchThis上致电myCustomObject

您可以看到示例here

相关问题