Does Browser load a whole block of JavaScript Before its execution?

有些话、适合烂在心里 提交于 2019-12-25 03:44:37

问题


Below is valid javascript code:

<script>
  foo();

  function foo()
  {
    alert("foo");
  }
</script>

The function foo is invoked before its declaration. So, I think browser must load the whole block script before its execution. By "whole block", I mean a open tag to a clos tag or a external javascript file. Is this true?


回答1:


Function statements are subject to hoisting. This means that regardless of where a function is declared, it is moved to the top of the scope in which it is defined.

(function () {
  foo();

  function foo() {
    alert('foo is beign called');
  }
}());

At compile time the structure of that code would change to:

(function () {
  function foo() {
    alert('foo is beign called');
  }

  foo();
}());

Function statements are not the only that are subject of hoisting, the var statement also, because of that (and because JavaScript haves only function-scope) is recommended to have only one var statement at the top of a function, for example:

var bar = "baz"; // on the outer scope
(function () {
  alert(bar); // bar is undefined

  var bar = "other value";
}());

The alert shows undefined, because internally the code changed to this:

var bar = "baz";
(function () {
  var bar;
  alert(bar); // bar is undefined

  bar = "other value";
}());



回答2:


If a method or variable is undefined, it throws an error "undefined" but if it is declared but not assigned a value then js won't throw any error.

<script>
  foo();

  function foo()
  {
    alert("foo");
  }
</script>

But your code will not throw any exception and also you can debug your javascript code easily. Here is a nice video shows how to debug js codes : Debugging with Firebug




回答3:


When I paste that JS into Firebug, I get "foo is not defined".

Most implementations of JS will load the entire file, and then execute it. The statements in the file are executed in order, so the call to the function foo occurs before its definition, which is an error as required by the ECMA 262 standard section 8.7.1



来源:https://stackoverflow.com/questions/1512358/does-browser-load-a-whole-block-of-javascript-before-its-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!