Why can I use a function before it's defined in JavaScript?

前端 未结 7 1748
日久生厌
日久生厌 2020-11-22 16:07

This code always works, even in different browsers:

function fooCheck() {
  alert(internalFoo()); // We are using internalFoo() here...

  return internalFoo         


        
7条回答
  •  情话喂你
    2020-11-22 16:39

    The function declaration is magic and causes its identifier to be bound before anything in its code-block* is executed.

    This differs from an assignment with a function expression, which is evaluated in normal top-down order.

    If you changed the example to say:

    var internalFoo = function() { return true; };
    

    it would stop working.

    The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases.

    This is documented in the ECMAScript standard, section 10.1.3. Unfortunately ECMA-262 is not a very readable document even by standards-standards!

    *: the containing function, block, module or script.

提交回复
热议问题