tommyd456 tommyd456 - 6 months ago 46
Javascript Question

Self invoking anonymouse functions with document parameter

I'm trying to understand the difference between:

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


(function() {
//do stuff with document

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


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

To this:

(function(a) {
    //do stuff with a

Notice the a, which is shorter than your document.