Explain the encapsulated anonymous function syntax

后端 未结 10 1620
时光说笑
时光说笑 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:18

    I have just another small remark. Your code will work with a small change:

    var x = function(){
        alert(2 + 2);
    }();
    

    I use the above syntax instead of the more widely spread version:

    var module = (function(){
        alert(2 + 2);
    })();
    

    because I didn't manage to get the indentation to work correctly for javascript files in vim. It seems that vim doesn't like the curly braces inside open parenthesis.

提交回复
热议问题