Javascript immediately invoked function patterns

后端 未结 5 374
既然无缘
既然无缘 2020-12-08 05:34

What do you call these patterns? What is the difference between them? When would you use each? Are there any other similar patterns?

(function() {
    con         


        
相关标签:
5条回答
  • 2020-12-08 06:09

    Self invoking anonymous function. The function body will be invoked immediately.

    (function() {
        console.log(this);  // window
    })();
    

    Self invoking function. The function body will be invoked immediately. You can still refer to the function x inside the function body. So when you want to execute something immediately, and then you may want to iterate it, you can just reference to it directly.

    (function x() {
        console.log(this);  // window
        console.log(x);     // function x() {}
    })();
    

    The self invoking anonymous function on the right side will be invoked immediately, and the returned value will be assigned to the y. Usually it has a return value when you use this pattern, otherwise, y will be undefined.

    var y = (function() {
        console.log(this);  // window
    })();
    

    IMO, it is same as the third one. The parentheses of the 3rd enclosing the function are just for making the function look like one entire thing. But the functionalities of the both are the same.

    var z = function() {
        console.log(this);  // window
    }();
    

    Similar to the 2nd one, but you can reference the x outside the function scope by using:

    (x = function () {
        console.log(this);  // window
        console.log(x);     // function x() {}
    })();
    console.log(x);         // function x() {}
    
    0 讨论(0)
  • 2020-12-08 06:28

    Here are your functions again with some comments describing when/why they might be useful:

    (function() {
        // Create a new scope to avoid exposing variables that don't need to be
        // This function is executed once immediately
    })();
    
    (function fact(i) {
        // This named immediately invoked function is a nice way to start off recursion
        return i <= 1 ? 1 : i*fact(i - 1);
    })(10);
    
    var y = (function() {
        // Same as the first one, but the return value of this function is assigned to y
        return "y's value";
    })();
    
    var z = function() {
        // This is the exact same thing as above (except it's assigned to z instead of y, of course).
        // The parenthesis in the above example don't do anything since this is already an expression
    }();
    
    0 讨论(0)
  • 2020-12-08 06:31

    In this case they are all semantically identical. The ECMAScript specification contains the full production rules, so this is a gross simplification.

    Also note that I am ignoring the named function's name (x) as the name is not used; it could be referenced within the body but since it is a FunctionExpression (via the grammar production) it would never (in a correct JS implementation) contaminate the containing scope - see the comments.

    (function() {
        console.log(this);  // window
    })();
    
    (function x() {
        console.log(this);  // window
    })();
    
    var y = (function() {
        console.log(this);  // window
    })();
    
    var z = function() {
        console.log(this);  // window
    }();
    

    Reduced (the bodies are inconsequential in this case, they all "return undefined"):

    (function() {})();
    
    (function x() {})();
    
    var y = (function() {})();
    
    var z = function() {}();
    

    Reduced (in the ECMAScript grammar FunctionExpression is a production rule, but here I use it to mean "an expression that is a function"):

    FunctionExpression()
    
    FunctionExpression()
    
    var y = FunctionExpression()
    
    var z = FunctionExpression()
    

    Ignoring the assignment of the result (which would always be undefined) it can be seen that all forms are the same.

    Happy coding.

    0 讨论(0)
  • 2020-12-08 06:31

    (function() { 'use strict'; you can use this type

    Why?: An IIFE-Immediately Invoked Function Expression removes variables from the global scope. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions.

    Why?: When your code is minified and bundled into a single file for deployment to a production server, you could have collisions of variables and many global variables. An IIFE protects you against both of these by providing variable scope for each file.

    0 讨论(0)
  • 2020-12-08 06:31

    It's time to use ES06, Here are your functions using arrow function from ES06.

     (() => {
        // Create a new scope to avoid exposing variables that don't need to be
        // This function is executed once immediately
    })();
    
    (fact = (i)=>(
      // This named immediately invoked function is a nice way to start off recursion
      i <= 1 ? 1 : i*fact(i - 1)
    ))(10)
    
    const y = (() => (
        // Same as the first one, but the return value of this function is assigned to y
         "y's value"
    ))();
    
    const z = (() => {
        // This is the exact same thing as above (except it's assigned to z instead of y, of course).
        // The parenthesis in the above example don't do anything since this is already an expression
    })();
    
    0 讨论(0)
提交回复
热议问题