Explain the encapsulated anonymous function syntax

后端 未结 10 1621
时光说笑
时光说笑 2020-11-21 07:02

Summary

Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but

10条回答
  •  别那么骄傲
    2020-11-21 07:15

    (function(){
         alert(2 + 2);
     })();
    

    Above is valid syntax because anything passed inside parenthesis is consider as function expression.

    function(){
        alert(2 + 2);
    }();
    

    Above is not valid syntax. Because java script syntax parser looks for function name after function keyword since it doesn't find anything it throws an error.

提交回复
热议问题