3

Possible Duplicate:
How does this JavaScript/JQuery Syntax work: (function( window, undefined ) { })(window)?

i see this pattern in the jquery source code (line 13), where they rebind 'window' and 'undefined' to locals:

(function(window, undefined) {
     window.something = 42;
     var dummy = 42 === undefined;
}(window));

i think rebinding 'window' to a local is a strict mode thing (prevents accidental access to window) - but look at how they are binding undefined to a local as well. why?

Community
  • 1
  • 1
Dustin Getz
  • 19,902
  • 13
  • 77
  • 127

2 Answers2

2

In JavaScript you can assign a value to undefined, for example:

undefined=42;

The jQuery notation ensures that within the block undefined is really undefined.

According to MDN:

Starting in JavaScript 1.8.5, undefined is non-writable, as per the ECMAScript 5 specification.

Christophe
  • 24,147
  • 23
  • 84
  • 130
  • I think this should stick to the standard. The JS 1.8.5 reference if I am not wrong is a Mozilla thingy – Alexander Dec 21 '12 at 23:00
1

If someone somehwere changes undefined behavior of you code will be unpredicatbale:

 undefined = 42;

So you force undefined in your function to be always correct by not passing that argument during the call:

 function safe(undefined) {
   // undefined is really undefined here
 }

 function unsafe() {
   // undefined could be 42 here
 }

 undefined = 42;
 safe();
 unsafe();

Similar with window. Also passing window in give you additional adantage that you can test your function without actually impacting real window. I.e. your "mock" window can have custom setTimeout to test timing behavior of the function.

 function complex(window)
 {
    window.setTimeout(callback, 1000);
 } 

 var mockWindow = {setTimeout:...};
 complex(mockWindow);
 // here you can make sure setTimout was called and if necessary
 // call the callback.
Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159