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

3

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.