Javascript immediately invoked function patterns

后端 未结 5 373
既然无缘
既然无缘 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: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.

提交回复
热议问题