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

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

Consider the following code.



Notice that a

相关标签:
3条回答
  • 2021-01-19 04:37

    function b() doesn't exist until the call a(function b() {}); is executed.

    JS doesn't search the code for functions, that way. Also, function b() {} isn't a function declaration, you're merely passing it as a parameter. The only way to access that function would be within function a():

    function a() {console.log(arguments[0])}
    a(function b() {});
    //function b() {}
    

    However, this does not mean that you can actually call b() inside a(), since b() is defined in the scope of a's function call, not in the function itself. Basically, the name b is useless.

    0 讨论(0)
  • 2021-01-19 04:46

    Inside a(function b() {});, the function is a function expression and not a function declaration (only which are hoisted). You might have a look at var functionName = function() {} vs function functionName() {} for the difference.

    0 讨论(0)
  • 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() {}
    
    0 讨论(0)
提交回复
热议问题