This question has already been answered:

Hello, I'm new to JS. I decided to look into the jquery source and the question literally arose on the first function:

(function( window, undefined ) { [...] window.jQuery = window.$ = jQuery; })(window); 

And the construction is not clear ( )(window) what is it?

Reported as a duplicate at Grundy. javascript Dec 3 '16 at 4:04 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • window is an argument to anonymous and self-calling function - mix

1 answer 1

This is the so-called self-invoking anonymous function to which the argument is passed. It is mainly used to isolate a piece of code from the external environment, and to prevent global area of ​​view from clogging. Called immediately after the announcement.

It is worth noting that in the example above there is a potential error. It is usually recommended to put a semicolon before declaring a self-calling function:

 ;(function(){ /* code */ })() 

This will avoid problems when merging several modules into one file, for example, by running this code, you will get not exactly the expected result:

 // module 1 var myFunc = function (str) { alert(str); } // Module 2 (function () { return 'blablabla'; }()); 
  • and in what situations is it necessary? that is, alert() in the code and (function() {alert();}()); will give a call - Jarry Roxwell