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

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

    Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.

    That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.

提交回复
热议问题