在jQuery中匿名函数包装器的目的是什么? [英] What is the purpose of the anonymous function wrapper in jQuery?
问题描述
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.
现在,我记得在脚本开发的早期,undefined实际上被定义为其他东西(我是还记得那个吗?)那是否与此相关?
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?
推荐答案
包装器做了很多事情:
function(window,undefined)
为函数提供窗口
和 undefined
变量
匿名调用})(窗口);
将窗口变量传递给脚本。
the anonymous call })(window);
passes the window variable to the script.
如果用户覆盖了window对象,他们可以很容易地修改脚本以使用正确的窗口
变量,即:
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);
缺少第二个参数设置 undefined
变量的值为 undefined
,这可以防止程序员通过覆盖 undefined
来搞乱jQuery。
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
.
这篇关于在jQuery中匿名函数包装器的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!