What is the purpose of a self executing function in javascript?

前端 未结 19 2849
清酒与你
清酒与你 2020-11-21 04:22

In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...
         


        
19条回答
  •  时光说笑
    2020-11-21 04:46

    Here's a solid example of how a self invoking anonymous function could be useful.

    for( var i = 0; i < 10; i++ ) {
      setTimeout(function(){
        console.log(i)
      })
    }
    

    Output: 10, 10, 10, 10, 10...

    for( var i = 0; i < 10; i++ ) {
      (function(num){
        setTimeout(function(){
          console.log(num)
        })
      })(i)
    }
    

    Output: 0, 1, 2, 3, 4...

提交回复
热议问题