The definition and use of function execution scene immediately

First, what is immediately execute the function?

Declare a function, and immediately call this anonymous function is called to perform the function immediately; it can be said to perform a function immediately grammar, let your function performed immediately after the definition;

To create a function to perform immediately, look:

Second, the immediate execution of the function of writing:

Sometimes, after we define the function, the function is called immediately, this time can not be directly added in parentheses after the function definition, which produces a syntax error. The reason is a syntax error, function keyword, either as a statement, can also be used as an expression, such as the following:

// statements 
function Fn () {};

// expression 
var Fn = function () {};
To avoid ambiguity resolution, JS engine provides that if the function appears at first, will be resolved to the statement. So JS engine keywords to see the beginning of the line is a function later that this period is a function definition, it should not end with the original brackets, so the error.
The solution is not to let the function appear at the beginning, let JS engine will be understood as an expression of the most simple process is to put a parenthesis, such as the following:
(function(){
//code
}())

(function (){
//code
})()
Two way top, are beginning with parentheses, the engine would mean is followed by an expression, rather than a function definition statement, so errors are avoided, which is called "function expression called immediately."
Immediate execution function, there are some other wording (plus some small things, not parsed into statement can be), such as the following:
( Function () {Alert ( "I am the anonymous function")} ())    // parentheses wrap the whole expression 
( function () {Alert ( "I am the anonymous function")}) ()   // brackets the function wrap 
! function () {Alert ( "I am the anonymous function")} ()   // negated, we do not care how much value, just by checking grammar 
+ function () {Alert ( "I am the anonymous function " )} () 
 - function () {Alert (" I am the anonymous function " )} () 
 ~ function () {Alert (" I am the anonymous function " )} () 
 void  function () {Alert (" I am anonymous function " )} () 
 new new  function () {Alert (" I am the anonymous function ")} ()

Third, the immediate implementation of the role functions:

  • You do not have a function name, to avoid the contamination of global variables
  • 立即执行函数内部形成了一个单独的作用域,可以封装一些外部无法读取的私有变量
  • 封装变量
总而言之:立即执行函数会形成一个单独的作用域,我们可以封装一些临时变量或者局部变量,避免污染全局变量

四、使用场景

1.怎样使以下alert的结果为0,1,2:

<body>
    <ul id="list">
        <li>公司简介</li>
        <li>联系我们</li>
        <li>营销网络</li>
    </ul>
    <script>
       var list = document.getElementById("list");
      var li = list.children;
      for(var i = 0 ;i<li.length;i++){
        li[i].onclick=function(){
          alert(i);  // 结果总是3.而不是0,1,2
        }
      }
     </script>  
</body>
为什么alert总是3? 因为i是贯穿整个作用域的,而不是给每一个li分配一个i,点击事件使异步,用户一定是在for运行完了以后,才点击,此时i已经变成3了。
那么怎么解决这个问题呢,可以用立即执行函数,给每个li创建一个独立的作用域,在立即执行函数执行的时候,i的值从0到2,对应三个立即执行函数,这3个立即执行函数里边的j分别是0,1,2所以就能正常输出了,看下边例子:
<body>
    <ul id="list">
        <li>公司简介</li>
        <li>联系我们</li>
        <li>营销网络</li>
    </ul>
    <script>
       var list = document.getElementById("list");
      var li = list.children;
      for(var i = 0 ;i<li.length;i++){
       ( function(j){
            li[j].onclick = function(){
              alert(j);
          })(i); //把实参i赋值给形参j
        }
      }
     </script>  
</body>

当然,也可以使用ES6的块级作用域解决整个问题:

<body>
    <ul id="list">
        <li>公司简介</li>
        <li>联系我们</li>
        <li>营销网络</li>
    </ul>
    <script>
      var list = document.getElementById("list");
      var li = list.children;
      for(let i = 0 ;i<li.length;i++){
        li[i].onclick=function(){
          alert(i);  // 结果是0,1,2
        }
      }
     </script>  
</body>

2.如何避免了污染全局变量

某些代码只需要执行一次,比如只需要显示一个时间,但是这些代码也需要一些临时的变量,但是初始化过程结束之后,就再也不会被用到,如果将这些变量作为全局变量,不是一个好的主意,我们可以用立即执行函数——去将我们所有的代码包裹在它的局部作用域中,不会让任何变量泄露成全局变量,看如下代码:

 

比如上面的代码,如果没有被包裹在立即执行函数中,而是直接以非函数的形式直接写在<script>标签里面,虽然也会立即执行,但是临时变量todaydom,days,today,year,month,date,day,msg都将成为全局变量(初始化代码遗留的产物)。
而用立即执行函数之后,这些变量都不会在全局变量中存在,以后也不会其他地方使用,有效的避免了污染全局变量。

Guess you like

Origin www.cnblogs.com/vickylinj/p/12191958.html