Probing into the execution process _javascript techniques of JavaScript statements

Source: Internet
Author: User
Tags define function function definition script tag

Nonsense not much to say, went straight to the topic. The operating principles of JavaScript are summarized as follows:

1. Execute JavaScript code in the order of HTML document flow

Browsers are step-by-step through the flow of documents to parse the page structure and information, JavaScript code as an embedded script as part of the HTML document, so the JavaScript code at the time of loading the execution order is based on the script tag <script> is determined by the order in which they appear.

If you introduce an external. js file through the script tag <script> src attribute, it will also execute in the order in which the statements appear, and the execution process is part of the document loading. It will not be deferred because it is an external JS file.

2. Pre-compilation and execution order relationships

First look at the following code:

<script type= "Text/javascript" >
function Hello () {
alert ("Hello");
}
Hello ();
function Hello () {
alert ("Hello World");
}
Hello ();
</script>

The output from this JS code is Hello World and Hello World, instead of first exporting hello and then exporting Hello World. This is because JavaScript does not interpret execution exactly in order, but before it is interpreted, it compiles the JavaScript one at a time, and in the precompiled process, the defined function is executed first, and all VAR variables are created with the default value of undefined. To improve the efficiency of program execution. In other words, the above code is actually a JS engine precompiled into the following:

<script type= "Text/javascript" >
var hello = function () {
alert ("Hello");
Hello = function () {
alert ("Hello World");
Hello ();
Hello ();
</script>

The above code can clearly see that the function is also a variable, you can assign the function. To prevent the previous occurrence, 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>

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

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

If you use this method to define function functions, you will be able to make an error and the error message is shown in Figure 1 below:

The error here is "not" a funtion, which is because at the time of precompilation, for variables declared with VAR, the variable value is undefined, although it was first processed. And then run hello (), because the front hello is undefined, the type is not OK, so here is the Hello is not a function. Although the program has the definition of this function, but the location of the definition is placed in the back of the call, then the call, the program does not run here, so useless.

Let's look at the following code:

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

The above code, although the call is also in front of the function definition, but here is defined by the Functions keyword, when defined by the function, and Var, the function definition has been assigned to the value of the past, so it can be run here.

Summarize:

When the JavaScript engine parses the script, it processes all declared variables and functions during the precompiled period. Processed as follows:

(1) A similar "precompiled" operation is performed before execution: first, the active object in the current execution environment is created, and those variables declared with VAR are set to the properties of the active object, but at this point the assignment of those variables is undefined. The functions defined as function are also added as properties of the active object, and their values are exactly the definition of the function.

(2) In interpreting the execution phase, when a variable needs to be resolved, it is first looked up from the active object in the current execution environment, and if it is not found and the owner of the execution environment has the prototype attribute, it is looked up from the prototype chain, otherwise it will be looked up in the scope chain Encountered var a = ... Such statements are assigned to the corresponding variable (note: The assignment of the variable is done in the interpretation execution phase, and if the variable is used before, its value will be undefined).

(3) In summary, a sentence summed up is: the declaration of variables in the precompiled period, the initialization of the variable in the operating period.

<script type= "Text/javascript" >
alert (a);//During precompilation the A variable is already loaded, but is defined with Var, so the assignment is undefined first, so the output is undefined here.
var a = 1;//This assigns a value of 1 alert (a) to the previously unassigned a
;//The output of A is already previously assigned, so output is 1.
</script>

For the above code, the output is: first output undefined, after output 1, analysis see code comments.

Although variable and function declarations can be anywhere in the document, it is good practice to declare global variables and functions before all JavaScript code and initialize the variables. Inside the function, you declare the variable first and then reference it.

3. Execute JavaScript code by block

A code block is a code snippet separated by a <script> label. When the JavaScript interpreter executes the script, it executes by block. In layman's parlance, when a browser parses an HTML document stream, if it encounters a <script> tag, the JavaScript interpreter waits until the code block is loaded, precompiling the code block before executing. After execution, the browser continues to parse the following HTML document stream, and the JavaScript interpreter is ready to process the next block of code. Because JavaScript is executed in blocks, a syntax error is prompted if a variable or function declared in a later block is invoked in a JavaScript block.

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

The above code, because it is two blocks of code, first executes the first block of code, and then executes the second block of code. When executing the first block of code, variable A does not declare, so an error is made, and the error message is: ' A is ' not defined.

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

Although JavaScript is executed by block, different blocks belong to the same global scope, meaning that variables and functions between blocks can be shared. So, the above two blocks of code run, although it is two blocks of code, but after the first run, a variable exists in the global scope, then run to the second code block, the output of a variable can call the global scope of a, so there is no problem.

4. Change the JavaScript execution order with the aid of event mechanism

Because JavaScript handles code in chunks and follows the parsing order of the HTML document stream, this syntax error is seen in the example above. However, when the document flow is loaded, this error will not occur if you access it again. For security reasons, we typically allow JavaScript code execution after the page is initialized, which avoids the effect of speed on JavaScript execution, and also avoids the HTML document flow restrictions on JavaScript execution.

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
 
 

Windows.onload = function () indicates that a function is first added to the triggering event, not executed immediately, but is executed after the entire page has been loaded, and the function is started. So, before Windows.onload executes, some variables have been loaded into the global zone, so there is no problem. The above output is: First output BB, then output cc, and finally output a.

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
 
 

If there is more than one Windows.onload event handler on a page, only the last one is valid (as shown in the previous code), in order to solve this problem, all scripts or call functions can be placed in the same onload event handler, as shown in the following code:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
 
 

5. Sequence of execution of JavaScript output scripts

In JavaScript development, JavaScript scripts are often exported using the write () method of the Document object. The document.write () method writes the output script string to the document location where the script resides, and the browser continues to parse the contents of the document.write () output after parsing the contents of the document.write (). Then parse the following HTML document in order. In other words, the code string that the JavaScript script outputs is executed immediately after the output. Note that JavaScript script strings that are output using the document.write () method must be placed in <script> tags that are also exported, otherwise the JavaScript interpreter will not be able to recognize these legitimate JavaScript codes. As an ordinary string, it is displayed in the page document. However, there is a risk of exporting scripts and executing through the document.write () method, because different JavaScript engines have different order of execution, and bugs occur when different browsers parse.

The above is a small set to introduce the JavaScript statement of the implementation process, I hope to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.