Hoe does this function construct using window and undefined as arguments work? [duplicate]
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.
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.
精彩评论