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

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

    I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":

    1. Better namespace management (Avoiding Namespace Pollution -> JS Module)
    2. Closures (Simulating Private Class Members, as known from OOP)

    The first one has been explained very well. For the second one, please study following example:

    var MyClosureObject = (function (){
      var MyName = 'Michael Jackson RIP';
      return {
        getMyName: function () { return MyName;},
        setMyName: function (name) { MyName = name}
      }
    }());
    

    Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.

    Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.

    Let us try some experiments:

    I can get MyName using getMyName and it works:

     console.log(MyClosureObject.getMyName()); 
     // Michael Jackson RIP
    

    The following ingenuous approach would not work:

    console.log(MyClosureObject.MyName); 
    // undefined
    

    But I can set an another name and get the expected result:

    MyClosureObject.setMyName('George Michael RIP');
    console.log(MyClosureObject.getMyName()); 
    // George Michael RIP
    

    Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.

提交回复
热议问题