Self-invoking function jQuery [duplicate]

流过昼夜 提交于 2019-12-07 14:41:24

问题


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

回答1:


The short answer: To prevent variable name conflicts. It is not always needed, but good practice in order to create conflict free reusable code.

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

In this instance undefined is simply used for readability to indicating that no more arguments are passed to the function.




回答2:


In case you want to avoid conflict regarding use of $

function( $ ) {
  ...
}( jQuery );

Inside this function you can use $ without having to worry about it's use outside of it as inside that function, $ always refers to the jQuery object.

This is helpful while creating jQuery plugins,You will see jQuery plugin's use this kind of function to avoid conflicts with other plugins.

Reference : http://learn.jquery.com/plugins/basic-plugin-creation/




回答3:


In function scope $ is local variable that not conflict with any other global $.



来源:https://stackoverflow.com/questions/17319718/self-invoking-function-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!