javascriptiife

Need help understanding a javascript function


I'm hoping someone can explain the following usage of JavaScript.

I have a page with a script that looks like this:

(function($){
     // code 
     // and stuff
})(jQuery);

I'm trying to understand what this code does, specifically:

  1. The opening parenthesis at the start
  2. The usage of the $ symbol
  3. The jQuery in parentheses at the end

thanks!


Solution

  • This is an anonymous function.

    The specific example you provide is usually used when jQuery (which uses the "$") is conflicting with another library (prototype also uses "$").

    What this does is say that whenever "$" is used within the function, it is to reference the jQuery object.

    Normal:

    $("foo").doStuff()
    

    Conflict avoidance:

    jQuery("foo").doStuff()
    

    Using anonymous function to avoid conflict:

    (function($){
      $("foo").doStuff();
    })(jQuery)