Javascript Anonymous Self-Launch Function to Close Area

Possible duplicate:
What are the benefits of using (function (window, document, undefined) {...}) (window, document)?

More and more often I see this code in the libraries that I used:

(function (window) { var Foo = function () { } window.Foo = Foo; })(window); 

The argument I saw for this is to avoid working in the global scope when creating (pseudo) classes. But, correct me, if I am mistaken, I always understood that this window is a global space. I suppose when you create a global variable, you add the property to the window anyway ... If this does not change strictly for ES5?

So basically, what's the point? The only advantage that I can see in code organized in this way is that you want to easily change the namespace of your classes later by passing an argument other than a window.

+4
source share
3 answers

Infact, strict mode throws an exception if you forget to use var for any variable declaration. But it works even without using external closure.

Using this template is much more to protect yourself from the outside world of javascript. For example, some other scripts overwrite window.undefined or any other variable, you can capture the value in this closure to access it from the inside.

for instance

 (function _myApp( win, doc, undef ) { // app code }( this, this.document )); 

In addition, when declaring variables with var or creating function declarations, they are always stored in the current activation object, respectively, in the Lexical environment record. This means that without using a Function context, you can easily rewrite methods and variables from some other point, because they will all be stored in the current Context (which would be global)

So:

 (function _myApp( win, doc, undef ) { var myVar = 42; function myFunc() { } }( this, this.document )); (function _myModule( win, doc, undef ) { var myVar = 42; function myFunc() { } }( this, this.document )); 

This works because of closure and context, but if you use the same code without function context, we will obviously rewrite our myVar and myFunc . This can happen everywhere, in the same file or in another loaded script.

+2
source

As evil as global variables, you must have at least one or no access to your script. The code you provided is one way to create this global variable. I prefer this way:

 window.Foo = (function () { var func = function () { // ... }; return { func: func }; })(); 
0
source

That's right, but the difference is that the code inside the function acts like an automatic init function.

 (function (window) { var Foo = function () { } var Bar = 69; // not in global scope window.Foo = Foo; // in global scope })(window); 

Unlike

 var Foo = function () { // in global scope } var Bar = 69; // in global scope 

and

 var Foo = function () { // in global scope } function init () { var Bar = 69; // not in global scope } init(); 
0
source

Source: https://habr.com/ru/post/1441297/


All Articles