Why does this "(jQuery)" exist at the end of the function?

1

I would like to know why this (jQuery) statement exists at the end of function .

jQuery(function($){

    // alert('Oi');
    $(".widgets-holder-wrap").removeClass('closed');

})(jQuery);
    
asked by anonymous 29.07.2015 / 16:02

1 answer

2

When you write (function() { ... })() you are making the code inside the function literal, so that the whole object is actually a function. Then you are invoking the function, with () at the end. This is used to control the visibility of functions and variables. JQuery plugins are usually written like this.

Being a function, you can pass whatever you want on () at the end. For example:

(function(jQ) { ... })(jQuery)

This is the definition of a function that receives a jQ parameter (known only in the context of the function) that is then called by passing a parameter (which in this case is external, a reference to jQuery).

Working in this way has some advantages:

  • You can redefine a global parameter and give it a meaningful name in that local context.
  • There is a small gain in performance since it is faster to search for something in the local scope and not to search the entire range of scopes to the global.
  • There are benefits to compressing your javascript.
29.07.2015 / 16:33