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

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

    Short answer is : to prevent pollution of the Global (or higher) scope.

    IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.

    This is the other way to write IIFE expression. I personally prefer this following method:

    void function() {
      console.log('boo!');
      // expected output: "boo!"
    }();
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

    From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.

提交回复
热议问题