1. 定义
IIFE: Immediately Invoked Function Expression,意为立即调用的函数表达式,也就是说,声明函数的同时立即调用这个函数。
对比一下,这是不采用IIFE时的函数声明和函数调用:
function foo(){ var a = 10; console.log(a); } foo();
下面是IIFE形式的函数调用:
(function foo(){ var a = 10; console.log(a); })();
(function foo(){ var a = 10; console.log(a); })();
列表2:IIFE写法二
(function foo(){ var a = 10; console.log(a); }());
var a = 2; (function IIFE(global){ var a = 3; console.log(a); // 3 console.log(global.a); // 2 })(window); console.log(a); // 2
function myModule(){ var someThing = "123"; var otherThing = [1,2,3]; function doSomeThing(){ console.log(someThing); } function doOtherThing(){ console.log(otherThing); } return { doSomeThing:doSomeThing, doOtherThing:doOtherThing } } var foo = myModule(); foo.doSomeThing(); foo.doOtherThing(); var foo1 = myModule(); foo1.doSomeThing();
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();
6. 小结
IIFE的目的是为了隔离作用域,防止污染全局命名空间。
ES6以后也许有更好的访问控制手段(模块?类?),有待研究。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211379.html原文链接:https://javaforall.net
