What is the advantage of using function (window, document, undefined)

2

I've noticed for a long time that many libraries are using something like:

(function(window, document, undefined){
    //exemplo de script
    console.log(window, document);
})(window, document);

or

(function(window, document, undefined){
    console.log(window, document);
}(window, document));

This really brings the edge when developing something like:

(function(){
    console.log(window, document);
})();
  

Note: If undefined is a normal variable and can be changed undefined = "new value"; which would make comparison with var a; if (a === undefined) { ... } impossible

    
asked by anonymous 28.12.2014 / 18:23

3 answers

4

IIFE functions are generally used in this way to safeguard which variables fall into the global scope.

An IIFE is a self-executing function, and it generates a new scope within itself.

Passing as a parameter of the function window and document is not very useful, but has a function that is to facilitate / optimize in code compression.

If there are many times in the code within this function the variables window or document then a JavaScript compressor like Uglify will shorten and give a letter to those variables, thus minimizing the file size.

The case of undefined is more interesting.

Sometimes you make the mistake of overwriting this variable. In other words, it is possible (in some browsers) to undefined = 20 . In this case all lines of code that use undefined to check if a variable is set will give unexpected values. Creating a function with 3 parameters but only calling / using 2 causes the third party to receive the actual value of undefined . Thus, for browsers that allow rewriting undefined this trick re-establishes its original value.

The other advantage and reason for undefined there is the same as above: for code compressors to be able to transform n times the 9-character word "undefined" into a single letter. >     

28.12.2014 / 20:54
1

I know the question is old, but since you've linked it in an answer, it's worth adding some details.

  • It is useful to pass objects in this way for testing purposes.

  • When developing on node, the window variable does not exist. In this case it is possible to do something like this:

    (function(window) {
        window.sayHello = function() {};
    })(typeof window !== 'undefined' ? window : this);
    

Note: this is the process that jquery uses.

The question about undefined is to ensure that the variable actually represents the undefined value since it can be overwritten.

    
04.08.2015 / 20:49
0

They use more for undefined same, sometimes it can be defined in some way and can disrupt the code.

Example

undefined = 'foo';
var bar;
bar === undefined; // FALSE

(function (undefined) {
    var bar;
    bar === undefined; // TRUE
})();
    
28.12.2014 / 19:40