什么是立即执行函数?有什么作用?

这是 JS 中的一个常见概念,面试时经常会被问到,请「用自己的语言」简述

  1. 立即执行函数是什么
  2. 立即执行函数有什么用途

1. 立即执行函数是什么

立即执行函数就是

  1. 声明一个匿名函数
  2. 马上调用这个匿名函数

上面是一个典型的立即执行函数。

  • 首先声明一个匿名函数 function(){alert(‘我是匿名函数’)}。
  • 然后在匿名函数后面接一对括号 (),调用这个匿名函数。

那么为什么还要用另一对括号把匿名函数包起来呢?

其实是为了兼容 JS 的语法。

如果我们不加另一对括号,直接写成

function(){alert('我是匿名函数')}()

浏览器会报语法错误。想要通过浏览器的语法检查,必须加点小东西,比如下面几种

(function(){alert('我是匿名函数')} ()) // 用括号把整个表达式包起来
(function(){alert('我是匿名函数')}) () //用括号把函数包起来
!function(){alert('我是匿名函数')}() // 求反,我们不在意值是多少,只想通过语法检查。
+function(){alert('我是匿名函数')}()
-function(){alert('我是匿名函数')}()
~function(){alert('我是匿名函数')}()
void function(){alert('我是匿名函数')}()
new function(){alert('我是匿名函数')}()

2. 立即执行函数有什么用?

只有一个作用:创建一个独立的作用域。

这个作用域里面的变量,外面访问不到(即避免「变量污染」)。

以一个著名的面试题为例:

var liList = ul.getElementsByTagName('li')
for(var i=0; i<6; i++){
  liList[i].onclick = function(){
    alert(i) // 为什么 alert 出来的总是 6,而不是 0、1、2、3、4、5
  }
}

为什么 alert 的总是 6 呢,因为 i 是贯穿整个作用域的,而不是给每个 li 分配了一个 i,如下:

那么怎么解决这个问题呢?用立即执行函数给每个 li 创造一个独立作用域即可(当然还有其他办法):

var liList = ul.getElementsByTagName('li')
for(var i=0; i<6; i++){
  !function(ii){
    liList[ii].onclick = function(){
      alert(ii) // 0、1、2、3、4、5
    }
  }(i)
}

在立即执行函数执行的时候,i 的值被赋值给 ii,此后 ii 的值一直不变。

i 的值从 0 变化到 5,对应 6 个立即执行函数,这 6 个立即执行函数里面的 ii 「分别」是 0、1、2、3、4、5。

以上,就是立即执行函数的基本概念。

完。

作者:方应杭

58 thoughts on “什么是立即执行函数?有什么作用?”

  1. Hi are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any coding expertise to make your own blog? Any help would be really appreciated!|

  2. Hi there, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam remarks? If so how do you protect against it, any plugin or anything you can recommend? I get so much lately it’s driving me crazy so any assistance is very much appreciated.|

  3. of course like your web site but you need to check the spelling on several of your posts. A number of them are rife with spelling issues and I find it very bothersome to tell the truth then again I will definitely come again again.|

  4. Hi there! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I’m getting sick and tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.|

  5. Hello there, There’s no doubt that your blog might be having browser compatibility issues. When I look at your web site in Safari, it looks fine however, if opening in IE, it’s got some overlapping issues. I just wanted to give you a quick heads up! Besides that, great website!|

  6. Nice post. I learn something totally new and challenging on blogs I stumbleupon every day. It’s always helpful to read articles from other writers and practice a little something from other sites. |

  7. What’s up everybody, here every person is sharing such familiarity, therefore it’s pleasant to read this blog, and I used to go to see this website every day.|

  8. I’m curious to find out what blog system you’re working with? I’m experiencing some minor security problems with my latest website and I would like to find something more risk-free. Do you have any recommendations?|

  9. I don’t even know how I ended up here, but I thought this post was good. I do not know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!|

  10. Today, I went to the beach front with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!|

  11. It is not my first time to pay a visit this web site, i am visiting this website dailly and obtain fastidious information from here daily.|

  12. Greetings! I’ve been following your web site for some time now and finally got the courage to go ahead and give you a shout out from Dallas Tx! Just wanted to tell you keep up the fantastic work!|

  13. When I originally commented I seem to have clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get 4 emails with the exact same comment. Is there a way you are able to remove me from that service? Thanks a lot!|

  14. I think that is among the most significant info for me. And i am glad reading your article. But want to remark on some basic things, The website style is wonderful, the articles is in point of fact nice : D. Just right job, cheers|

  15. Oh my goodness! Amazing article dude! Thank you so much, However I am experiencing difficulties with your RSS. I don’t know why I can’t join it. Is there anybody having identical RSS problems? Anybody who knows the answer will you kindly respond? Thanks!!|

  16. An intriguing discussion is definitely worth comment. I think that you ought to write more on this topic, it might not be a taboo subject but usually people do not speak about these subjects. To the next! Kind regards!!|

  17. hello there and thank you for your info – I have definitely picked up anything new from right here. I did however expertise a few technical issues using this site, since I experienced to reload the website many times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage your quality score if advertising and marketing with Adwords. Well I am adding this RSS to my email and can look out for much more of your respective intriguing content. Ensure that you update this again very soon.|

  18. Nice post. I learn something totally new and challenging on blogs I stumbleupon everyday. It will always be exciting to read through content from other writers and use something from other sites. |

  19. I do not even understand how I stopped up here, however I thought this submit was once great. I do not realize who you are however certainly you are going to a well-known blogger in the event you aren’t already. Cheers!|

  20. I’m not sure exactly why but this web site is loading very slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later and see if the problem still exists.|

发表评论

电子邮件地址不会被公开。