说一说JS的IIFE

本文介绍了立即调用的函数表达式(IIFE)的概念及其在JavaScript中的应用,包括IIFE的作用、常见形式、如何构造单例模式等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 定义

[html]  view plain  copy
  1. function foo(){  
  2.   var a = 10;  
  3.   console.log(a);  
  4. }  
  5.    
  6. foo();  
[html]  view plain  copy
  1. (functionfoo(){  
  2.   vara=10;  
  3.   console.log(a);  
  4. })();  

 为什么需要IIFE?

 IIFE的常见形式

列表 1:IIFE写法一
[html]  view plain  copy
  1. (function foo(){  
  2.   var a = 10;  
  3.   console.log(a);  
  4. })();  

列表 2:IIFE写法二
[html]  view plain  copy
  1. (functionfoo(){  
  2.   vara=10;  
  3.   console.log(a);  
  4. }());  

其实,IIFE不限于()的表现形式[ 1],但是还是遵守约定俗成的习惯比较好。

 IIFE的函数名和参数

根据《You Don’t Know JS:Scope & Clouses》[ 2]的说法,尽量避免使用匿名函数。但是IIFE确实只执行一次,给IIFE起个名字有些画蛇添足了。如果非要给IIFE起个名字,干脆就叫IIFE好了。
[html]  view plain  copy
  1. var a = 2;  
  2. (function IIFE(global){  
  3.     var a = 3;  
  4.     console.log(a); // 3  
  5.     console.log(global.a); // 2  
  6. })(window);  
  7.    
  8. console.log(a); // 2  

 IIFE构造单例模式

[html]  view plain  copy
  1. functionmyModule(){  
  2.   varsomeThing="123";  
  3.   varotherThing=[1,2,3];  
  4.    
  5.   functiondoSomeThing(){  
  6.     console.log(someThing);  
  7.   }  
  8.    
  9.   functiondoOtherThing(){  
  10.     console.log(otherThing);  
  11.   }  
  12.    
  13.   return{  
  14.     doSomeThing:doSomeThing,  
  15.     doOtherThing:doOtherThing  
  16.   }  
  17. }  
  18.    
  19. varfoo=myModule();  
  20. foo.doSomeThing();  
  21. foo.doOtherThing();  
  22.    
  23. varfoo1=myModule();  
  24. foo1.doSomeThing();  
[html]  view plain  copy
  1. var myModule=(functionmodule(){  
  2.   varsomeThing="123";  
  3.   varotherThing=[1,2,3];  
  4.    
  5.   functiondoSomeThing(){  
  6.     console.log(someThing);  
  7.   }  
  8.    
  9.   functiondoOtherThing(){  
  10.     console.log(otherThing);  
  11.   }  
  12.    
  13.   return{  
  14.     doSomeThing:doSomeThing,  
  15.     doOtherThing:doOtherThing  
  16.   }  
  17. })();  
  18.    
  19. myModule.doSomeThing();  
  20. myModule.doOtherThing();  

 小结

引用

1 Ben Alman, “Immediately-Invoked Function Expression (IIFE)“.
2 Kyle SimpsonYou Don’t Know JS:Scope & Clouses (2014).

原文地址:http://softlab.sdut.edu.cn/blog/subaochen/2016/02/%E8%AF%B4%E4%B8%80%E8%AF%B4js%E7%9A%84iife/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值