tommyd456 tommyd456 - 8 days ago 8
Javascript Question

Self invoking anonymouse functions with document parameter

I'm trying to understand the difference between:

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


and

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


I'm unsure why the convention appears to be to pass
document
and sometimes
window
too to the function? Is it to do with scope?

Answer

There are some reasons for this:

1. Using less global variables By injecting the function with the global variable it will depend on only the argument and not a global variable which might be used multiple times.

2. Creating a locasl scope An IIFE is a way to create a new scope by declaring a function and immediatly invoking it. See this question for more information.

3. Better minify

For example if you will minify your example it will change from this:

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

To this:

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

Notice the a, which is shorter than your document.

Comments