2

I get a *.js file code similar like:

(function(a){ 

   a("#div_element").removeClass("show message");
 
   ....

})(jQuery); 

I'm trying to understand:

  1. What is (function(a){...})(jQuery); ?

  2. How to use it?

  3. What is a here? Because I seen normal code looks like:

    $("#div_element").removeClass("show message");

Community
  • 1
  • 1
wordpressquestion
  • 745
  • 1
  • 7
  • 18
  • Similar Question : http://stackoverflow.com/questions/2464635/what-does-function-jquery-do-mean – xkeshav May 24 '11 at 05:42
  • possible duplicate of [What does this mean? (function (x,y)){...}){a,b); in JavaScript](http://stackoverflow.com/questions/3921922/what-does-this-mean-function-x-y-a-b-in-javascript) – Guffa May 24 '11 at 05:44
  • Other similar questions: http://stackoverflow.com/questions/4806150/javascript-function-vs-function, http://stackoverflow.com/questions/5192227/javascriptwhat-function-mean, http://stackoverflow.com/questions/4043647/what-does-this-function-a-function-inside-brackets-mean-in-javascript, http://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-a-javascript-object-function-class-declaration-me – Guffa May 24 '11 at 05:47

2 Answers2

2

function( a ){ /* … */ } is an anonymous function that is directly called with jQuery as parameter. So a inside the anonymous function is the same as jQuery

From jQuery website

Example: Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.

jQuery.noConflict();
(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

read this post also:

What does (function( $ ){...})( jQuery ); do/mean?

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245
1

Maybe it's easier to understand the mechanism by thinking of it this way:

(function( blah ) {
    blah("hello");
}) ( alert );

Note how blah becomes a proxy for alert. This is just a fancy way of not polluting the global namespace (a lot of libraries use the $ as a global variable).

David Titarenco
  • 32,662
  • 13
  • 66
  • 111