Discuss the execution process of JavaScript statement

  • 2020-12-10 00:35:29
  • OfStack

Without further ado, let's get 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 parses the page structure and information from top to bottom in a stream of documents, and the javascript code is part of the html document as an embedded script, so the order in which the javascript code is executed when loaded is also based on the script tag < script > To determine the order of occurrence.

If passed by the script tag < script > The src attribute is used to introduce the external.js file, so it will also be executed in the order in which its statements appear, and the execution process is part 1 of the document load. It will not delay execution because it is an external js file.

2. Relationship between precompilation and execution order

First, take a look at this code:


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

The above js code outputs hello world and hello world instead of hello and then hello world. This is because javascript does not interpret execution exactly in order. Instead, javascript is precompiled once before interpretation. During the precompilation, defined functions are prioritized and all var variables are created with the default value of undefined to improve the execution efficiency of the program. This means that the above code is actually precompiled by the JS engine to look like this:


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

As you can clearly see from the above code, functions are also variables and can be assigned values. To prevent the previous situation, you can define 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>

The first file above, where I put hello() before function, also outputs the correct result.


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

If the function function is defined in this way, an error is reported, as shown in Figure 1 below:

The error of hello is not a funtion is due to the fact that the variable declared with var is the value of undefined at precompilation time, although it is processed first. Then when running hello(), hello is not a function since the previous hello is undefined, the type is not determined. So, the function is defined in the program, but it's defined at the end of the call, so when it's called, the program isn't running here, so it doesn't work.

Consider the following code:


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

Although the above code is also called before the function definition, it is defined with the function keyword, which is not the same as var. function has assigned the value of the function, so it can be run here.

Conclusion:

When the javascript engine parses the script, it processes all declared variables and functions at precompile time. The treatment is as follows:

(1) before the execution will be carried out in a similar "precompiled" operation: first will create a current execution environment of active objects, and those who use var statement variable is set to the activities of the object's properties, but the variable assignment is undefined, and those with function define attributes of the object function is also added for activities, and their values is the function definition.

(2) In the interpretation execution stage, when a variable needs to be resolved, it will first look for it from the active object of the current execution environment; if it is not found and the owner of the execution environment has prototype attribute, it will look for it from the prototype chain; otherwise, it will look for it according to the scope chain. Meet var a =... Such a statement will assign values to the corresponding variable (note: the assignment of the variable is done during the interpretation execution, and if used before that, its value would be undefined).

(3) To sum up, the declaration of variables is in the pre-compile period, and the initialization of variables is in the run period.


<script type="text/javascript">
alert(a); //  During precompilation a The variable is loaded, but used var By definition, so the assignment is undefined First, so output here undefined . 
var a = 1; //  There's nothing assigned to the first one a I'm going to assign it to 1
alert(a); //  The output here a Already assigned, so output 1 . 
</script>

For the above code, the output result is: undefined first, then 1. See the code note for analysis.

While variable and function declarations can be anywhere in the document, a good practice is to declare global variables and functions before all JavaScript code and initialize the variable assignment. Variables are also declared and referenced inside functions.

3. Execute javascript code by block

A block of code is a use < script > Tag-separated code snippets. The JavaScript interpreter executes scripts in chunks. In layman's terms, when a browser parses an HTML document stream, it encounters one < script > The JavaScript interpreter waits until the block is loaded and precompiles the block before executing it. Once executed, the browser continues to parse the HTML document stream below, and the JavaScript interpreter is ready to handle the next block of code. Since JavaScript is executed in blocks, you will be prompted with a syntax error if you call a variable or function declared in a subsequent block in an JavaScript block.


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

The above code, since it is two blocks, executes the first block and then the second. The variable a was not declared when the first block was executed, so the error message was: a is not defined.


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

Although JavaScript is executed in blocks, different blocks belong to the same global scope, which means that variables and functions between blocks can be shared. So, when these two blocks of code are running, they are two blocks, but after the first block is run, the a variable is in global scope. When you run to the second block, the output a variable can call a in global scope, so there is no problem.

4. Change the execution order of javascript with the help of event mechanism

Because JavaScript handles code in blocks while following the parsing order of the HTML document stream, you will see this syntax error in the example above. However, when the document stream is loaded, this error will not occur if it is accessed again. To be safe, we generally do not allow JavaScript code to execute until after the page has been initialized, which avoids the network speed impact on JavaScript execution and avoids the limitations of HTML document flow on JavaScript execution.


<!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() means to add a function to the triggering event, not to execute immediately, but to start executing the event after the entire page has been loaded, and function. So, before windows.onload executes, 1 variable has been loaded into the global area, so there is no problem. The output above is: 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);
};
//  The above onload Will not execute, will only execute the following onload
window.onload = function() {
alert("onload2");
};
</script>
<script>
var a = 1;
alert("bb");
</script>
</head>
<body>
</body>
<script>
alert("cc");
</script>
</html>

If there are multiple ES168en.onload event handlers in one page, only the last one will be valid (as shown in the code above). To solve this problem, you can put all scripts or call functions in the same onload event handler, as shown in the following code:


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

5. Execution order of javascript output script

In JavaScript development, the write() method of the document object is often used to output JavaScript scripts. The document. write() method writes the output script string to the document location where the script resides. The browser parses the output of document. write() after parsing the contents of the document location of document. write(), and then parses the following HTML documents sequentially. That is, the code string output by the JavaScript script is executed immediately after the output. Note that the JavaScript script string output using the document.write () method must be placed at the same time as the output < script > Otherwise, the JavaScript interpreter will not recognize the valid JavaScript code and will appear as a normal string in the page document. However, there is a definite risk that the script will be output and executed using the document.write () method, because it will be executed in different order by different JavaScript engines, and Bug will appear when parsed by different browsers.

Above is the site to introduce the JavaScript statement execution process, I hope to help you.


Related articles: