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

前端 未结 19 2788
清酒与你
清酒与你 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:58

    First you must visit MDN IIFE , Now some points about this

    • this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
    • This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

提交回复
热议问题