0

Possible Duplicate:
How does the (function() {})() construct work and why do people use it?

Learning JavaScript, I came across this function:

(function(window, undefined){
  // …
})(window);

I’m wondering what type of function this is and how I can call it.

Community
  • 1
  • 1
  • Agreed, I'm answering this only for the `window` and `undefined` arguments, which is not covered in the "duplicate" and IMO it actually makes sense to explain... – Christian C. Salvadó Oct 10 '10 at 02:26

1 Answers1

2

It's a widely used pattern that allows you to have a local scope to declare all your variables, without pollute the global scope.

Is simply a FunctionExpression being immediately invoked, the window argument is used mostly to shorten the identifier lookup to the local scope.

In the browser environment window is a property of the global object, that points to the global object itself, if it exists on the local scope, resolving will be faster.

About the undefined argument, it is used to ensure that you can use it without worries, in some implementations (in fact all ECMAScript 3 based implementations) the undefined global property ( window.undefined ) is mutable, meaning that someone can change its value to e.g.:

window.undefined = true;

Breaking your script.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838