Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  29] [ 2]  / answers: 1 / hits: 42199  / 14 Years ago, mon, april 26, 2010, 12:00:00

Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it's encapsulated in the following way:



(function( window, undefined ) {

//All the JQuery code here
...

})(window);


I've read an article on JavaScript Namespacing and another one called An Important Pair of Parens, so I know some about what's going on here.



But I've never seen this particular syntax before. What is that undefined doing there? And why does window need to be passed and then appear at the end again?


More From » jquery

 Answers
47

The undefined is a normal variable and can be changed simply with undefined = new value;. So jQuery creates a local undefined variable that is REALLY undefined.



The window variable is made local for performance reasons. Because when JavaScript looks up a variable, it first goes through the local variables until it finds the variable name. When it's not found, JavaScript goes through the next scope etc. until it filters through the global variables. So if the window variable is made local, JavaScript can look it up quicker.
Further information: Speed Up Your JavaScript - Nicholas C. Zakas


[#96963] Friday, April 23, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
halie

Total Points: 362
Total Questions: 99
Total Answers: 119

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;