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

前端 未结 19 2845
清酒与你
清酒与你 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 05:10

    It's all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.

    For example, as mentioned in a comment by Alexander:

    (function() {
      var foo = 3;
      console.log(foo);
    })();
    
    console.log(foo);

    This will first log 3 and then throw an error on the next console.log because foo is not defined.

提交回复
热议问题