C
C
Cake_Seller2010-10-20 00:00:17
JavaScript
Cake_Seller, 2010-10-20 00:00:17

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

3 answer(s)
A
apangin, 2010-10-20
@Cake_Seller

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);

This makes it possible to use a shorthand like $(xxx) in a script, even if the $ identifier is defined somewhere else, such as in MooTools.
PS And this, by the way, is not a closure.

[
[email protected]><e, 2010-10-20
@barmaley_exe

Well, you can save a couple of bytes.

A
Anton Korzunov, 2010-10-20
@kashey

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 question

Ask a Question

731 491 924 answers to any question