开发者

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

开发者 https://www.devze.com 2023-02-02 04:49 出处:网络
jQuery starts off wrapping all of it\'s code in an anonymous function: (function ( window, undefined) {

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 functi开发者_JS百科on 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?


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.

0

精彩评论

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