简体   繁体   中英

Why can I call functions declared later in the same script block, but not ones declared in later script blocks?

I use this below cod and it works as expected:

<script>
  function_two();
  function function_two() {
    alert("The function called 'function_two' has been called.");
  }
</script>

But when I apply to this code below, it doesn't work as expected:

<script>
  function_two();
</script>

<script>
  function function_two() {
    alert("The function called 'function_two' has been called.");
  }
</script>

Can someone say why?

This is because of function declaration hoisting . function declarations are hoisted to the top of the script. In the first case, what has actually happened is this:

<script>
  function function_two() {
      alert("The function called 'function_two' has been called.");
  }

  function_two();
</script>

The function declaration has been hoisted above the function_two() call.

In the second case, function_two() is contained within a different script element, and the function declaration cannot be hoisted above it - the code in this case remains in the same order, and function_two() ultimately doesn't exist when it is called.

Due to the hoisting of javascript, declarations always get shoved to the top of a scope before execution (you can't see that, js does that itself). That's why you can use the function in your first example before you declared it.

In your second example you use seperate script elements for function declaration and usage. That is not possible, since the first script element get's compiled and executed before the browser starts to compile the second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM