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

前端 未结 7 1743
日久生厌
日久生厌 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:54

    The browser reads your HTML from beginning to end and can execute it as it is read and parsed into executable chunks (variable declarations, function definitions, etc.) But at any point can only use what's been defined in the script before that point.

    This is different from other programming contexts that process (compile) all your source code, perhaps link it together with any libraries you need to resolve references, and construct an executable module, at which point execution begins.

    Your code can refer to named objects (variables, other functions, etc.) that are defined further along, but you can't execute referring code until all the pieces are available.

    As you become familiar with JavaScript, you will become intimately aware of your need to write things in the proper sequence.

    Revision: To confirm the accepted answer (above), use Firebug to step though the script section of a web page. You'll see it skip from function to function, visiting only the first line, before it actually executes any code.

    0 讨论(0)
提交回复
热议问题