Strange JavaScript syntax like this: (function(){//code}) ();?

后端 未结 8 545
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 06:31

What does the below JavaScript mean? Why is the function embedded inside ()?

(function() {
    var b = 3;
    a += b;
}) ();
8条回答
  •  孤城傲影
    2020-12-11 07:09

    It's functionaly equivalent to doing something like:

    var myFunc = function(){
        var b = 3;
        a += b;
    };
    
    myFunc();
    

    It's got the parenthesis around it (and trailing) so that the function is called immediately. As others have said, the concept is called an anonymous function.

提交回复
热议问题