Why is there such a "(jQuery)" at the end of Function?

Asked

Viewed 52 times

1

I wonder why there is this instruction (jQuery) at the end of function.

jQuery(function($){

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

})(jQuery);
  • This may help. http://simplesideias.com.br/design-patterns-no-javascript-module

1 answer

2


When you write (function() { ... })() you are making the code within the literal function (literal Function), so that the whole object is actually a function. Then you are calling the function, with the () 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 to us () at the end. For example:

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

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

Working in this way brings some advantages:

  • You can reset a global parameter and give it a meaningful name in that local context.
  • There is a small performance gain as it is faster to search for something in the local scope and not search the entire scope chain to the global.
  • There are benefits to compressing your javascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.