Answer the question
In order to leave comments, you need to log in
What does a construction like “(function(d){ ... })(document)” mean?
Repeatedly met a similar construction:
It is clear to me that this code uses a closure, but it is not clear why the Document object is passed as an argument to a closed function .
Here is a concrete example - a small Javascript utility that makes it so that in IE you can set styles for HTML5 elements (such as section, header, article and others; by default, styles for these elements in IE will be ignored). This script uses the following construction:
In this example, in addition to the document argument, the this argument is also passed , which, as I understand it, stores the Window object
(function (d) {
// Какой-то код
})(document);
(function (p, e) {
// Какой-то код
})(this, document);
. Who can prompt to me what for to the closed functions to transfer Document and Window as arguments ?
Answer the question
In order to leave comments, you need to log in
1. To limit the scope, i.e. avoid global variables.
2. To shorten the record of the call to the object.
3. As a special case of the 1st and 2nd, to avoid name conflicts. For example, when using jQuery, one often writes
(function($) { ... })(jQuery);
For me, this is the usual encapsulation of functionality.
And you can supply any variable as input, for example, an iframe document and not your own - the function will somehow be purple
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question