开发者

Hoe does this function construct using window and undefined as arguments work? [duplicate]

开发者 https://www.devze.com 2023-01-19 04:19 出处:网络
This question already has answers here: Closed 12 years ago. 开发者_开发知识库 Possible Duplicate:
This question already has answers here: Closed 12 years ago. 开发者_开发知识库

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消