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

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

    0 讨论(0)
  • 2020-11-21 04:55

    IIRC it allows you to create private properties and methods.

    0 讨论(0)
  • 2020-11-21 04:56
    (function(){
        var foo = {
            name: 'bob'
        };
        console.log(foo.name); // bob
    })();
    console.log(foo.name); // Reference error
    

    Actually, the above function will be treated as function expression without a name.

    The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.

    The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.

    0 讨论(0)
  • 2020-11-21 04:57

    Namespacing. JavaScript's scopes are function-level.

    0 讨论(0)
  • 2020-11-21 04:57

    It looks like this question has been answered all ready, but I'll post my input anyway.

    I know when I like to use self-executing functions.

    var myObject = {
        childObject: new function(){
            // bunch of code
        },
        objVar1: <value>,
        objVar2: <value>
    }
    

    The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...

    object: {
        childObject: {
            childObject: {<value>, <value>, <value>}
        }, 
        objVar1: <value>,
        objVar2: <value>
    }
    

    Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题