2008-12-23 64 views

回答

21

它使用函数体来提供自己的作用域,而不是引入大量的可能被外部代码意外改变的全局变量。

例如,

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

myCoolFunction(); 

如果功能范围并没有出台将有可能通过引入其他代码(或另一个库)

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

你说得对,这将防止全球污染意外改变someConstantValue命名空间。

jQuery所需的所有变量和函数都是在该函数内部创建的,这些函数和变量不会渗透到全局名称空间中。如果你看一下这个代码块:

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); 
}; 

它实际上是通过设置window.jQuery和窗口连接jQuery的初始化向外界$的初始化函数。这是包装函数内部的变量直接在包装外部可用的唯一地方。

还要注意整个函数是这样包装的(函数,,,)(),只要文件加载就会执行该函数。

相关问题