Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this block of JS code mean? [duplicate]

Tags:

javascript

Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

   (function(window){
              // some codes here
                    })(window);

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

like image 718
Codier Avatar asked May 16 '11 23:05

Codier


2 Answers

This is called a immediately-invoked anonymous function. (IIAF for short.)

In this case, you are defining a function that takes in a parameter called "window" that overrides the global window object inside of that scope.

The kicker here is that right after defining the function, you're immediately invoking it, passing in the global window object, so it is as if you used the global reference within the function closure!

Most of the time, the purpose of this is to avoid polluting the global namespace by way of wrapping all potential variables within an anonymous scope.

like image 192
Jacob Relkin Avatar answered Nov 02 '22 13:11

Jacob Relkin


As far your questions regarding window, the window in parentheses at the bottom is a reference to the global window object. The first window is just a name for a parameter. But in this instance it refers to the global window object since you're using an anonymous self-invoked function. You could call it monkeys and it wouldn't make a difference (of course, you'd have to use monkeys within the body of the anonymous function then, to refer to the parameter). So now, you now have a reference to the global window object within your function.

Yes, the function is invoked once and it is invoked as soon as it is defined. This is because it is a self-invoked anonymous function.

like image 40
Vivin Paliath Avatar answered Nov 02 '22 12:11

Vivin Paliath