Home  >  Article  >  Web Front-end  >  Discuss the execution process of JavaScript statements_javascript skills

Discuss the execution process of JavaScript statements_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:17:061470browse

Without further ado, let’s get straight to the point. The operating principle of javascript is summarized as follows:

1. Execute javascript code in the order of html document flow

The browser gradually parses the page structure and information from top to bottom according to the document flow. The javascript code is an embedded script and a component of the html document, so the execution order of the javascript code when loading is also based on the script tag baccc8a5f820dfdc87206d9cb2226ada, then it will also be executed in the order in which its statements appear, and the execution process is part of the document loading. Execution will not be delayed because it is an external js file.

2. The relationship between precompilation and execution order

First look at the following code:

<script type="text/javascript">
function hello() {
alert("hello");
}
hello();
function hello() {
alert("hello world");
}
hello();
</script>

The output result of the above js code is hello world, hello world, instead of outputting hello first and then hello world. This is because JavaScript is not interpreted and executed completely in order, but JavaScript is pre-compiled before interpretation. During the pre-compilation process, defined functions will be executed first, and all var variables will be created. By default The value is undefined to improve program execution efficiency. In other words, the above code is actually pre-compiled by the JS engine into the following:

<script type="text/javascript">
var hello = function() {
alert("hello");
};
hello = function() {
alert("hello world");
};
hello();
hello();
</script>

You can clearly see from the above code that functions are actually variables, and functions can be assigned values. In order to prevent the previous situation from occurring, it can be defined into two js files as follows:

<script type="text/javascript">
hello();
function hello() {
alert("hello");
}
// hello();
</script>
<script type="text/javascript">
function hello() {
alert("hello world");
}
hello();
</script>

In the first file above, I put hello() in front of the function, and the correct result can be output.

<script type="text/javascript">
hello();
var hello = function() {
alert("hello");
};
// hello();
</script>

If you use the above method to define the function function, an error will be reported. The error message is as shown in Figure 1 below:

The error hello is not a function is reported here. This is because during precompilation, although the variables declared with var are processed first, the variable value is undefined. Then when running hello(), since the previous hello is undefined and the type is not determined, here is hello is not a function. Although this function is defined in the program, the location of the definition is placed after the call, so when the call is made, the program does not run here, so it is useless.

Look at the following piece of code:

<script type="text/javascript">
hello();
function hello() {
alert("hello");
}
// hello();
</script>

Although the above code is called before the function definition, it is defined with the function keyword. When defined with function, it is different from var. When function is defined, the value of the function is already set. Assigned to the past, so it can be run here.

Summary:

When the JavaScript engine parses the script, it will process all declared variables and functions during pre-compilation. The processing is as follows:

(1) A similar "pre-compilation" operation will be performed before execution: first, an active object in the current execution environment will be created, and those variables declared with var will be set as attributes of the active object, but at this time these The assignments of variables are all undefined, and those functions defined with function are also added as properties of the active object, and their values ​​are exactly the definition of the function.

(2) During the interpretation and execution phase, when a variable needs to be parsed, it will first be searched from the active object of the current execution environment. If it is not found and the owner of the execution environment has the prototype attribute, it will be searched from the prototype chain. Search, otherwise it will be searched according to the scope chain. When a statement such as var a = ... is encountered, the corresponding variable will be assigned a value (note: the assignment of the variable is completed during the interpretation and execution phase. If the variable is used before this, its value will be undefined).

(3) To sum up, the summary in one sentence is: the declaration of variables is in the pre-compilation period, and the initialization of variables is in the runtime.

<script type="text/javascript">
alert(a); // 在预编译期间a变量已经加载,但是用var定义,所以赋值为undefined先,故这里输出undefined。
var a = 1; // 这里给前面的没有赋值的a进行赋值为1
alert(a); // 这里输出的a已经是前面赋值过的,所以输出1。
</script>

For the above code, the output result is: undefined is output first, and then 1 is output. For analysis, see the code remarks.

Although variable and function declarations can be anywhere in the document, it is a good practice to declare global variables and functions before all JavaScript code, and to initialize and assign variables. Within a function, variables are declared first and then referenced.

3. Execute javascript code in blocks

The so-called code block is a code segment separated by 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags. When the JavaScript interpreter executes a script, it executes it in blocks. In layman's terms, if the browser encounters a 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag when parsing the HTML document stream, the JavaScript interpreter will wait until the code block is loaded, pre-compile the code block, and then execute it. After execution, the browser will continue to parse the following HTML document flow, and the JavaScript interpreter will be ready to process the next block of code. Since JavaScript is executed in blocks, if you call a variable or function declared in a subsequent block in a JavaScript block, a syntax error will be prompted.

<script>
alert(a);
</script>
<script>
var a = 1;
</script>

上面的这段代码,由于是两个代码块,先执行完第一个代码块,再执行第二个代码块。执行第一个代码块的时候,变量a没有声明,所以报错,报错信息是:a is not defined。

<script>
var a = 1;
</script>
<script>
alert(a);
</script>

虽然说,JavaScript是按块执行的,但是不同块都属于同一个全局作用域,也就是说,块之间的变量和函数是可以共享的。所以,上面的这两个代码块运行的时候,虽然是两个代码块,但是第一段运行以后,a变量就存在了全局作用域中,此时运行到第二个代码块,输出的a变量就可以调用全局作用域中的a,所以没有问题。

4、借助事件机制改变javascript执行顺序

由于JavaScript是按块处理代码,同时又遵循HTML文档流的解析顺序,所以在上面示例中会看到这样的语法错误。但是当文档流加载完毕,如果再次访问就不会出现这样的错误。为了安全起见,我们一般在页面初始化完毕之后才允许JavaScript代码执行,这样可以避免网速对JavaScript执行的影响,同时也避开了HTML文档流对于JavaScript执行的限制。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>javascript</title>
<script>
window.onload = function() {
alert(a);
};
</script>
<script>
var a = 1;
alert("bb");
</script>
</head>
<body>
</body>
<script>
alert("cc");
</script>
</html>

windows.onload = function()表示先在触发事件上加一个函数,并不立即执行,而是在整个页面都加载完成以后再开始执行该事件,及function。所以,在windows.onload执行之前,就已经把一些变量加载到了全局区中,所以没有问题。上面的输出结果是:先输出bb,再输出cc,最后输出a。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>javascript</title>
<script>
window.onload = function() {
alert(a);
};
// 上面的onload不会执行,只会执行下面的onload
window.onload = function() {
alert("onload2");
};
</script>
<script>
var a = 1;
alert("bb");
</script>
</head>
<body>
</body>
<script>
alert("cc");
</script>
</html>

如果在一个页面中存在多个windows.onload事件处理函数,则只有最后一个才是有效的(如上面的代码所示),为了解决这个问题,可以把所有脚本或调用函数都放在同一个onload事件处理函数中,如下面的代码所示:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>javascript</title>
<script>
window.onload = function() {
// 放到一起
alert(a);
alert("onload2");
};
</script>
<script>
var a = 1;
alert("bb");
</script>
</head>
<body>
</body>
<script>
alert("cc");
</script>
</html>

5、javascript输出脚本的执行顺序

在JavaScript开发中,经常会使用document对象的write()方法输出JavaScript脚本。document.write()方法先把输出的脚本字符串写入到脚本所在的文档位置,浏览器在解析完document.write()所在文档内容后,继续解析document.write()输出的内容,然后才按顺序解析后面的HTML文档。也就是说,JavaScript脚本输出的代码字符串会在输出后马上被执行。请注意,使用document.write()方法输出的JavaScript脚本字符串必须放在同时被输出的3f1c4e4b6b16bbbd69b2ee476dc4f83a标签中,否则JavaScript解释器因为不能够识别这些合法的JavaScript代码,而作为普通的字符串显示在页面文档中。但是,通过document.write()方法输出脚本并执行也存在一定的风险,因为不同JavaScript引擎对其执行顺序不同,同时不同浏览器在解析时也会出现Bug。

以上所述是小编给大家介绍的JavaScript语句的执行过程,希望对大家有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn