自调用函数jQuery [英] Self-invoking function jQuery
问题描述
我注意到在某些地方,jQuery代码包装在如下所示的自调用函数中.为什么要这样做,在什么情况下有用,在什么情况下是不必要的样板?
I noticed that in some places, jQuery code is wrapped in a self-invoking function like below. Why is this done, in what cases is this useful and in what cases is an unnecessary boilerplate?
function( $ ) {
...
}( jQuery );
推荐答案
简短答案:防止变量名冲突.并非总是需要它,但是为了创建无冲突的可重用代码,这是一种很好的做法.
The short answer: To prevent variable name conflicts. It is not always needed, but good practice in order to create conflict free reusable code.
长答案:在javascript中,$符号只是另一个变量. jQuery之所以使用它,是因为它是一个很好的速记方式,而不必每次都键入jQuery,但是其他任何代码(包括其他库)也可以.
The long answer: In javascript the $ symbol is just another variable. jQuery uses it because it is a nice shorthand instead of having to type out jQuery each time, but so can any other code (including other libraries).
为防止与同一范围内的变量的其他用途(在本例中为$,在全局"范围内)发生冲突,通常将代码包装在带有无冲突"变量的自调用函数中作为函数参数传递.然后,这将创建一个新的作用域,其中您的变量将不会干扰该变量的其他使用.这样,您就可以传递完整的命名变量&可以在匿名函数中以您想要的任何名称使用它.
To prevent conflict with other uses of a variable at the same scope (in this case $ at the "global" scope) it is common for code to be wrapped in a self-invoking function with the "conflict-free" variables passed as the function parameters. This then creates a new scope where your variable won't interfere with other uses of that variable. That way you can pass the full named variable & uses it with whatever name you want within the anonymous function.
因此,在创建无冲突的可重用代码时,使用此方法是一个好习惯:
So, when creating conflict free reusable code it is good practice to use this methodology:
(function( $ ) {
...
})( jQuery );
沿着这些行,您还将看到以下格式:
Along these lines you will also see the following format:
(function( $, window, undefined ) {
...
})( jQuery, window );
在这种情况下,undefined
只是为了提高可读性,以指示没有更多的参数传递给该函数.
In this instance undefined
is simply used for readability to indicating that no more arguments are passed to the function.
这篇关于自调用函数jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!