2010-11-17 17 views
0

在很多情况下,我已经看到jQuery如何修改this关键字以使对象具有实际存在的优势。太棒了......在自定义方法中使用jQuery'this'关键字

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

例如:

var myCustomObject = { 

    myCustomValue: 1, 

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

}; 

如果使用jQuery的回调称为 “本” 就是现在jQuery的 “上下文”,显然对myCustomValue返回undefined。

我已经注意到,我可以参考实例直接如

switch (myCustomObject.myCustomValue) {} 

但这似乎冗长烦人,我不知道,如果任何意外的负面影响可以通过这个引起...

什么是否适合这种情况?

回答

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可以称为任何你想要的。

+0

我是否抽烟或者是否在最后失踪了一个右括号? PS:你刚刚也解释了疯狂的语法,我无法用它声明的方式让我的头在jQuery库本身。对于像这个例子这样的小对象,它更有意义。谢谢亲爱的先生:-) – 2010-11-17 04:08:00

+0

@Maxim,谢谢,我在paren中加入了。基本上,这个语法只是一个匿名构造函数。 – 2010-11-17 04:13:07

+1

'self'的其他热门选择是'me'和'that'。 – Domenic 2010-11-17 04:26:23

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

然后只需调用patchThismyCustomObject

您可以看到一个示例here

相关问题