2012-01-27 27 views
2

我試圖圍繞Javascript的function.apply()來打包頭。您可以使用這樣的: f.apply(obj,args)當你將它設置爲一個jQuery集時,理解function.apply中的「this」arg

與給定的參數args運行功能f,與功能的映射到對象objthis內部使用。

這裏有一個簡單的例子來說明如何,所有的工作讓我們先進的速度:

var o = { 
    state : 0, 
    plus : function(){ 
    this.state += 1; 
    } 
} 
//o is an object with a state-tracking var and a function that will operate on it 
o.state 
// 0 
o.plus() 
o.state 
// 1 
newO = {state:3} 
// newO is similar to the original object, but doesn't have that state-manipulating function 
newO.state 
// 3 
o.plus.apply(newO,[]) // call o's function, but hijack the 'this' reference to point to newO 
newO.state 
// 4 

酷。所以我寫了一個函數來解決在一個特定的jQuery插件的JavaScript中的空指針問題。如果一個jQuery集合是空的,它只是不運行的函數:

var applyIfPresent = function(jqObj,func,args){ 
    //only works if jquery has the func you supply 
    if(jqObj.length){ 
    jqObj[func].apply(jqObj,args); 
    } 
} 

我已經運行簡單的測試:applyIfPresent($("input"),"css",["background","blue"]); 要看看它是否會推廣到一個jQuery集合多個元素。它似乎工作正常,但我不知道jQuery的內部以及如何使用this轉換爲該架構。我喜歡它看起來像魔術一樣工作,但說實話? - 我學會了對魔法有點害怕。

f.apply或jQuery如何使它工作?

+1

的[來源的jQuery(https://github.com/jquery/jquery)可用。我不太確定問題是什麼,因爲它('Function.apply')只是「標準」的JavaScript ... – 2012-01-27 18:39:00

+0

你似乎知道'apply'是如何工作的,而且你似乎知道如何使用jQuery的API 。我想現在還不清楚究竟是什麼讓你感到困惑。你的'applyIfPresent()'函數可以處理任何帶'length'屬性的對象,不管是否使用jQuery。 – 2012-01-27 18:45:27

+1

您是否知道如果'length'爲零,jQuery方法是沒有操作的?即'applyIfPresent($(「input」),「css」,[「background」,「blue」])''''確實如同$(「input」)css(「background」,「blue」)' 。 – Domenic 2012-01-27 18:48:33

回答

2

它不是魔術,你似乎通過上面的例子完全理解它。
當你做

jqObj[func].apply(jqObj,args); 

它基本上一樣做

$(jqObj).func(args); 
相關問題