Which means construction of a type “(function(d){ ... })(document)”


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
6 views
Repeatedly met such a structure:

(function (d) {

// Some code

})(document);


I understand that this code uses a closure, but it is not clear why the argument of the closed-loop functions share the object Document.

Here is a concrete example — a small Javascript utilitywhich makes it so that in IE you can set the styles for HTML5 elements (like section, header, article and other; the default styles for these elements in IE should be ignored). This script uses the following design:

(function (p, e) {
// Some code
})(this, document);


In this example, in addition to the argument document in addition pass in an argument this, which, as I understand it, is stored in the object Window. Who can tell me why introverted functions to transfer the handling of arguments to Document and Window?
by | 6 views

3 Answers

0 like 0 dislike
1. To limit the scope, i.e. avoid global variables.
2. To reduce the case record to the object.
3. As a special case of the 1st and 2nd to prevent naming conflicts. For example, when using jQuery often write
\r
(function($) { ... })(jQuery);

Thanks to this script, you can use the short record of type $(xxx), even if the identifier $ is defined somewhere else, for example, in MooTools.
\r
P. S. And this, incidentally, is not shorted out.
by
0 like 0 dislike
Well, you can save a few bytes.
by
0 like 0 dislike
For me it is the usual encapsulation of functionality.
And at the entrance you can file any variable, for example the document of the iframe and not your functions might be purple
by

Related questions

0 like 0 dislike
4 answers
0 like 0 dislike
2 answers
asked Apr 11, 2019 by sddvxd
0 like 0 dislike
3 answers
asked Apr 25, 2019 by sorry_i_noob
110,608 questions
257,186 answers
0 comments
27,902 users