Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - What is the purpose of the anonymous function wrapper in jQuery?

jQuery starts off wrapping all of it's code in an anonymous function:

(function ( window, undefined) {
   /*
   ...jquery code...
   */
}) (window);

I get that the function is executed immediately upon the entire script being read, but what is the purpose of the arguments? One is a global object reference, the other is a property reference.

Now, I remember that earlier in the script development, undefined actually got defined as something else (am I remembering that right?). Was that related to this?

Also, it looks like the function is being used as an operator? Just like it is above, I don't understand the syntax of the statement at all. Maybe there is context that would help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The wrapper does a number of things:

function(window,undefined)

provides the window and undefined variables to the function

the anonymous call })(window); passes the window variable to the script.

If a user overrides the window object, they will easily be able to modify the script to use the correct window variable i.e.:

(function(window,undefined){})(w);

The lack of a second parameter being passed sets the undefined variable to have a value of undefined which prevents a programmer from messing up jQuery by overriding undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...