浏览器在执行之前是否会加载整个JavaScript块? [英] Does Browser load a whole block of JavaScript Before its execution?

查看:50
本文介绍了浏览器在执行之前是否会加载整个JavaScript块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是有效的javascript代码:

Below is valid javascript code:

<script>
  foo();

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

函数foo在其声明之前被调用.因此,我认为浏览器必须在执行之前加载整个块脚本.整块"是指对clos标签或外部javascript文件的打开标签.这是真的吗?

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?

推荐答案

函数声明必须进行吊装.这意味着无论在何处声明函数,都将其移至定义该函数的作用域的顶部.

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();
}());

函数语句不是唯一的悬挂主题, <代码还要使用> var 语句,因此(并且因为JavaScript具有唯一的功能范围)建议仅具有

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";
}());

警报显示 undefined ,因为内部代码已更改为:

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";
}());

这篇关于浏览器在执行之前是否会加载整个JavaScript块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆