What is the purpose of creating jQuery code inside these elements like this?

(function ($) { ... } ) (jQuery); 
+6
javascript jquery
source share
5 answers

To avoid conflicts with other javascript libraries that also use $ .

This method, however, allows you to use $ in this function as you wish, no need to use jQuery there.

This pattern is also important when writing jquery plugins.

+6
source share

It creates a function with $ as an argument and immediately runs this function with jQuery as an argument. Effectively, this ensures that $ points to jQuery inside your code, even if jQuery.noConflict() .

+2
source share

This way you can use $ inside your scope, but outside, jQuery does not interfere with the use of other $ libraries (for example, Prototype also uses $ , and some like to mix the two together)

+1
source share

In addition to the reason detailed in other answers, it is (a bit!) Faster for accessing function arguments than global variables.

Until jQuery.noConflict() was called, it could be written as function($){ … }($) with the same effect.

0
source share

Also called anonymous callback function, because it is not associated with any object, therefore it is strictly "functional". Good design when developing plugins with jQuery to avoid conflicts, as others have pointed out!

0
source share

All Articles