最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jul 25, 2011 at 10:10 skaffman 404k96 gold badges824 silver badges775 bronze badges asked Jan 4, 2011 at 21:13 DexterDexter 2452 gold badges4 silver badges17 bronze badges 1
  • It's the code from jQuery: code.jquery./jquery-1.4.4.js – Dexter Commented Jan 4, 2011 at 21:21
Add a ment  | 

1 Answer 1

Reset to default 11

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)

  1. 暂无评论