Function names defined as parameters to a function call aren't hoisted. Why not?

前端 未结 3 1898
灰色年华
灰色年华 2021-01-19 03:52

Consider the following code.



Notice that a

3条回答
  •  臣服心动
    2021-01-19 04:49

    EcmaScript §13 (see the paragraph below the NOTE) defines how Function Expressions and Function Declarations are handled.

    Function Declarations are instantiated when the EnvironmentRecord is built (§10.5) and thus hoisted, a Function Expression is evaluated later and it's optional Identifier is never visible to the enclosing scope.

    As this is a function expression, it's name is not visible to the outer scope. It's the same like

    a = function(){};  // valid as it is a function expression
    
    a = function b(){};// also valid
    
    // b is is not accessable here, same as the anonymous function, but a of course is.
    

    both are valid, but b is not visible to the outer scope. Omitting the name in a function declaration however is not valid.
    The optional Identifier of the function expression is for reference purposes inside the function body (e.g. to enable recursive calls).

    Update to your Update:

    The reason why the first console.log yields undefined instead of throwing an error is the hoisting (While the instantiation is hoisted the initialisation isn't):

      console.log(a); // undefined
      var a = function b() {};
      console.log(a); // function b() {}
    
      // equals (hoisted):
      var a;
      console.log(a); // undefined
      a = function b() {};
      console.log(a); // function b() {}
    

提交回复
热议问题