立即调用的函数通常用于创建一个局部函数范围,该范围是私有的,不能从外部世界访问,并且可以定义它自己的局部符号而不影响外部世界。这通常是一种很好的做法,但在这种特殊情况下,我认为它除了增加几行代码之外没有任何好处,因为它没有用于任何事情。
这段代码:
(function(exports){
exports.notGlobalFunction = function() {
console.log('I am not global');
};
}(module));
将与没有像这样立即调用的一段代码相同:
module.notGlobalFunction = function() {
console.log('I am not global');
};
不同的是,首先,为modules
被调用exports
创建了一个别名,该别名对于立即调用的功能块是本地的。但是,别名并没有做任何独特的事情,代码也可以modules
直接使用。
该变量modules
被创建为单个全局父对象,然后可以将许多其他全局变量作为属性。这通常被称为“命名空间”。这通常是一个很好的设计模式,因为它最大限度地减少了可能与同一项目/页面中使用的其他代码冲突的顶级全局变量的数量。
因此,不要像这样制作多个顶级变量:
var x, y, z;
可以像这样制作一个顶级变量:
var modules = {};
然后,将所有其他全局变量作为属性附加到它:
modules.x = 5;
modules.y = 10;
modules.z = 0;
这样,虽然仍有多个全局变量,但只有一个可能与其他代码冲突的顶级全局变量。
类似地,立即调用的函数会创建一个本地私有作用域,其中可以创建该作用域的本地变量,并且不会干扰其他代码段:
(function() {
var x, y, z;
// variables x, y and z are available to any code inside this immediately invoked function
// and they act like global variables inside this function block and
// there values will persist for the lifetime of the program
// But, they are not truly global and will not interfere with any other global
// variables and cannot be accessed by code outside this block.
// They create both privacy and isolation, yet work just as well
})();
将参数传递给立即调用的函数只是一种将值传递到立即调用的函数作用域的方法,该作用域将具有它自己的局部符号:
(function(exports) {
// creates a local symbol in this function block called exports
// that is assigned an initial value of module
})(module);