The sample code you provided is an example of a self-running function:
(function(){
The first set of parentheses defines a function: (anonymous function enclosed in parentheses)
(function() {})
This defines an anonymous function. He does nothing by himself. But if you add a set of parentheses () after the definition, it will be the same as the parentheses used to call the function. Try it:
(function(message) { alert(message); })("Hello World");
This creates a function that takes a parameter and displays a warning window containing the value provided. Then he immediately calls this function with the parameter "Hello World".
Your example defines a self-starting function. It takes a parameter called $ . The function is then immediately called with a jQuery reference passed as an argument.
This is common if you want jQuery to work in noConflict() mode (which removes the global reference to $ ).
In noConflict() mode, you can still access jQuery through the jQuery global variable, but most people prefer to use $ , so this self-awareness function takes the jQuery global variable as a parameter named $ as part of a function that leaves you the option to use the $ shortcut inside the self-running function when jQuery runs in noConflict () mode to avoid collisions with other libraries that use $ in the global scope.
Hope this answers your question!
ampersandre
source share