Self-tuning anonymous functions with a document parameter

I am trying to understand the difference between:

(function(document) {
    //do stuff with document
})(document);

and

(function() {
    //do stuff with document
})();

I am not sure why the agreement seems to transfer document, and sometimes windowalso functions? Is it related to the area?

+4
source share
3 answers

There are several reasons for this:

1. Using less global variables Introducing the function of a global variable, it will depend only on the argument, and not on the global variable, which can be used several times.

2. Creating a Local Area IIFE is a way to create a new area by declaring a function and immediately calling it. See this question for more information.

3.

, , :

(function(document) {
    //do stuff with document
})(document);

:

(function(a) {
    //do stuff with a
})(document);

a, , document.

:

+1

, /uglifier, UglifyJS. document a, .

-

(function(document, window){
  var body = document.body;
  var foo = document.querySelector('foo');
  var bar = document.querySelector('bar');
})(document, window);

(function(a, b){
  var c = a.body;
  var d = a.querySelector('foo');
  var e = a.querySelector('bar');
})(document, window);

, ;

(function(){
  var c = document.body;
  var d = document.querySelector('foo');
  var e = document.querySelector('bar');
})();
+6

(IIFE) . , , . document window JavaScript web api js . IIFE, , - . :

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

console.log(w); // Uncaught ReferenceError: w is not defined
console.log(a); // Uncaught ReferenceError: a is not defined

The reason wand ais not defined in the second set console.log, because they are locally attached to IIFE.

+2
source

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


All Articles