Explain the encapsulated anonymous function syntax

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

    Great answers have already being posted. But I want to note that function declarations return an empty completion record:

    14.1.20 - Runtime Semantics: Evaluation

    FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }

    1. Return NormalCompletion(empty).

    This fact is not easy to observe, because most ways of attempting to get the returned value will convert the function declaration to a function expression. However, eval shows it:

    var r = eval("function f(){}");
    console.log(r); // undefined

    Calling an empty completion record makes no sense. That's why function f(){}() can't work. In fact the JS engine does not even attempt to call it, the parentheses are considered part of another statement.

    But if you wrap the function in parentheses, it becomes a function expression:

    var r = eval("(function f(){})");
    console.log(r); // function f(){}

    Function expressions return a function object. And therefore you can call it: (function f(){})().

提交回复
热议问题