2010-11-17 18 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

相關問題