简体   繁体   English

为什么jQuery将自己包装在一个函数中?

[英]Why does jQuery wrap itself in a function?

I was reading the jQuery source and I was wondering why the entire source file was wrapped in an anonomous function. 我正在阅读jQuery源代码 ,我想知道为什么整个源文件都包含在一个自治函数中。

(function(){
  ...
})();

Is this something which helps not to pollute the global namespace? 这有助于不污染全局命名空间吗? Why is it there and how does it work? 它为什么存在,它是如何工作的?

It uses the function body to provide its own scope rather than introducing a large number of globals that could be accidentally changed by external code. 它使用函数体提供自己的范围,而不是引入大量可能被外部代码意外更改的全局变量。

Eg. 例如。

(function (){
    var someConstantValue = ...;
    myCoolFunction = function(){ return someConstantValue * 5; }
})();

myCoolFunction();

If the function scope were not introduced it would be possible to accidentally change someConstantValue by introducing other code (or another library) 如果未引入函数作用域,则可能会通过引入其他代码(或其他库)意外更改someConstantValue

someConstantValue = someOtherValue; // this won't change the behaviour of myCoolFunction

You're right that it will prevent pollution of the global namespace. 你是对的,它可以防止污染全局命名空间。

All of the variables and functions that jQuery needs are created inside of that function, which keeps those functions and variables from bleeding out into the global namespace. jQuery需要的所有变量和函数都是在该函数内部创建的,这使得这些函数和变量不会流入全局命名空间。 If you look at this block of code: 如果你看一下这段代码:

var jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
};

it's actually connecting the jQuery initializer to the outside world by setting window.jQuery and window.$ to the initialization function. 它实际上是通过将window.jQuery和window。$设置为初始化函数来将jQuery初始化程序连接到外部世界。 That's the only place where the variables inside the wrapper function are directly available outside of the wrapper. 这是包装函数内部变量直接在包装器外部可用的唯一位置。

Notice too that the whole function is wrapped like this (function,,,)() which will execute that function as soon as the file loads. 另请注意,整个函数都包含这样(函数,,,)(),它将在文件加载后立即执行该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM