2012-04-24 32 views
6

我想我明白模塊模式,但爲什麼一些例子,通過JQuery的是這樣的參數:模塊模式 - 爲什麼JQuery作爲參數傳入?

Namespace.AppName = (function ($) { 
    // Code Here 
})(jQuery); 

如果我沒有在JQuery中通過我仍然可以使用jQuery庫只生成細$()在模塊內調用。那麼爲什麼有些人這樣做呢?

+0

可能重複這個代碼[如函數參數jQuery的美元符號($)?](http://stackoverflow.com/questions/4983150/jquery-dollar-sign-as-function-argument) – 2012-04-24 11:03:51

回答

16

這裏的想法是,您將jQuery作爲$傳遞給裏面的函數,確保這個jQuery是$。這通常用於保護使用$的代碼,尤其是在使用jQuery以及其他類似mootools的使用$的庫時。


例如,如果你有在的<head>

<!--load jQuery--> 
<script src="jquery.js"></script> 

<script> 
    //"$" is jQuery 
    //"jQuery" is jQuery 
</script> 

<!--load another library--> 
<script src="anotherlibrary.js"></script> 

<script> 
    //"$" is the other library 
    //"jQuery" is jQuery 

    //out here, jQuery code that uses "$" breaks 

    (function($){ 
     //"$" is jQuery 
     //"jQuery" is jQuery (from the outside scope) 

     //in here, jquery code that uses "$" is safe 

    }(jQuery)); 

</script> 
+0

有道理!謝謝! – reach4thelasers 2012-04-24 11:34:09

+0

「$」是anotherlibrary.js將$定義爲全局時的另一個庫。我認爲 – 2013-07-12 17:53:05

1

爲了安全使用$''。大多數開發人員更喜歡使用'$'而不是jQuery。

將$作爲全局使用時,可能會與其他JS庫衝突。

0

這是爲了確保您的名稱空間/作用域使用$作爲jQuery而不是其他JS庫(如使用$的Prototype)。

1

這樣你就可以使用$作爲jQuery的捷徑。如果你不像這樣封裝它,有時可能會與其他庫衝突。

相關問題