IIFE: Immediately Invoked Function Expression,意为立即调用的函数表达式,也就是说,声明函数的同时立即调用这个函数。
我们经常看到只使用一次的函数,IIFE通常的目的是为了隔离作用域了!既然只使用一次,那么立即执行好了!既然只使用一次,函数的名字也省掉了!
function foo(){
var a = 10;
console.log(a);
}
foo();
(function foo(){
var a = 10;
console.log(a);
})()
IIFE构造单例模块
var myModule = (function module(){
var someThing = "123";
var otherThing = [1,2,3];
function doSomeThing(){
console.log(someThing);
}
function doOtherThing(){
console.log(otherThing);
}
return {
doSomeThing:doSomeThing,
doOtherThing:doOtherThing
}
})();
myModule.doSomeThing();
myModule.doOtherThing();











网友评论