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

后端 未结 8 535
爱一瞬间的悲伤
爱一瞬间的悲伤 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:12

    It's an anonymous function, that is called directly after creation, then thrown away.

    It's inside a parenthesis to prevent a syntax error. Without the parentheses the keyword function needs to be followed by an identifier.

    You can also do like this to put the function in a variable, and then call it:

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

    Notice that the parentheses are not needed when the function keyword is not first.

提交回复
热议问题