JavaScript plus sign in front of function expression

前端 未结 3 1530
清歌不尽
清歌不尽 2020-11-22 03:28

I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:

+function(){console.log(\"Something.\")}()
         


        
3条回答
  •  无人共我
    2020-11-22 03:56

    Subsidiary to @TJCrowder's answer, + is usually used to force numerical casting of a value as this SO answer explains. In this instance it is called the 'unary plus operator' (for ease of googling).

    var num = +variant;
    

    So in front of a function it can be a way to force the function's result to be interpreted as a number. I doubt it happens yet, but theoretically the JIT could use that to compile the function as a numerical-only function etc. However, to prevent the unary plus being a concatenation when used in a larger expression, you would need parentheses:

    blah + (+(function(){ var scope; return "4"; })());
    

提交回复
热议问题