Features of variable pre-parsing in JavaScript

Source: Internet
Author: User

JavaScript is an interpreted language without a doubt, but does it parse it from top to bottom at runtime? In fact, this does not prove to be the case. I learned through the JavaScript authoritative guide and relevant information on the Internet that JavaScript has a "pre-resolution" behavior. It is very important to understand this feature. Otherwise, you may encounter many unresolved problems in actual development, or even cause the existence of program bugs. In order to resolve this phenomenon, as a learning conclusion, this article gradually guides you to understand JavaScript "pre-parsing". If my opinion is incorrect, I hope to correct it.

Let's take an example:

Var lastName = "Gonn"; (function DisplayLastName () {console. log (lastName); var lastName = "Zeng"; console. log (lastName) ;}) (); // who can guess what the result is?

The output should be Gonn and then Zeng.

But the result is undefined Zeng. Why?

Javascript performs operations similar to "pre-resolution" before execution: first, an active object in the current execution environment is created, and set the variables declared with var to the attributes of the active object. However, the value assigned to these variables is undefined, and the functions defined by the function are also added as the attributes of the active object, and their values are exactly the definitions of functions.

In the execution phase of interpretation, when a variable needs to be parsed, the system first searches for the activity object in the current execution environment, if no prototype attribute is found and the execution environment owner has the prototype attribute, it will be searched from the prototype chain; otherwise, it will be searched by the scope chain. Var a =... Such a statement will assign values to the corresponding variables (note: the value of the variable is completed in the interpretation execution phase. If the variable is used before, its value will be undefined ).

That is to say, pre-resolution is performed first, and the var variable is assigned undefined. When the local variable has var, lastName exists as a local variable within the function. If var lastName = in the above function is changed to lastName =, the results will be different. In this case, the pre-resolution is not used as a local variable and the value is undefined.

Here are some examples.

function handle(){  alert(arg1);  } ;    handle();  var arg1 = 20;  

The result is undefined. Because the value of arg1 is printed before the interpretation of var arg1 = 20; at this time, no value is assigned to arg1.

handle();  var handle = function(){  alert(20);  };  

Result: handle is not a function. When handle () is executed, no value is assigned to handle-function definition. If changed:

handle();    var handle = function handle (){  alert(20);  };  

In IE, a dialog box is displayed, because it uses var handle... This sentence is also interpreted as a function definition, and the function definition should have a value during pre-compilation, so it can be executed. But in FF, it is still interpreted as a variable declaration, and the value is assigned only when the statement is executed.

Because of this, you should avoid using variables before they are initialized.

The following code is available for try/catch exceptions:

try{  alert(var1);  alert(varFun);  alert(Fun);  var var1 = 1;  var varFun = function(){};    function Fun(){alert(1);}  }  catch(e){  function Fun(){alert(2);}  }  

The running results of the above Code in IE and Chrome are undefined, undefined, and fuction () {alert (2 );}, the results in Firefox are undefined, undefined, and "Fun undefined. It is not clear how Firefox handles the "pre-resolution" of try/catch.

1. if JavaScript is parsed from top to bottom at runtime, it is understandable that the following code runs correctly, because we define a function before calling it.

function showMsg(){    alert('This is message');}showMsg(); // This is message

2. We also know that the following code can work normally after the function can be defined. It seems that showMsg () is not defined when showMsg () is called, but it works normally, it indicates that JavaScript is "pre-parsed.

showMsg(); // This is messagefunction showMsg(){    alert('This is message');}

3. The above is a function example. The following is an example of a common variable. In the following example, undefined is displayed, indicating that the msg in the first sentence is defined, but not initialized. It is the same as var msg; alert (msg. If you comment out the second sentence below, the "msg undefined" error will be reported. This also indicates that JavaScript is "pre-parsed.

alert(msg); //undefinedvar msg='This is message';

4. Let's take a look at an example to deepen the impression of "pre-parsing" JavaScript. The following code displays This is message 2 in the pop-up dialog box. Why? In fact, two functions with the same name are defined in the previous and later sections, and the showMsg () in the subsequent sections overwrites the previously defined functions (in JavaScript, variables with the same name will have the same overwrite problem ), the first showMsg () is decommissioned. Why is the second call of showMsg () Not the message 1 function defined above? This proves that JavaScript has a "pre-resolution" behavior.

showMsg(); // This is message 2function showMsg(){    alert('This is message 1');}showMsg(); // This is message 2function showMsg(){    alert('This is message 2');}

5. JavaScript "pre-resolution" is to pre-resolve variables or functions to the environment they can call (the runtime environment of variables. The following code seems to have seen the definition of msg before alert (msg), but the "msg undefined" error is still reported when the program runs. This is because the variables defined in the function are private variables of the function, it cannot be called directly outside, which indicates that JavaScript "pre-resolution" does not resolve all Defined variables to a global object, such as window.

Function showMsg () {var msg = 'this is message';} alert (msg); // msg is not defined

6. JavaScript "pre-resolution" is performed in segments, which is precisely divided into <script> blocks. The following code appears in two script blocks on the same page and defines three functions with the same name. The program running result indicates that the showMsg () of the second script block does not overwrite the first two showMsg (), while the second showMsg () of the first script block overwrites the first showMsg ().

<body><script type="text/javascript">showMsg(); //This is message 2function showMsg(){    alert('This is message 1');}function showMsg(){    alert('This is message 2');}</script><script type="text/javascript">function showMsg(){    alert('This is message 3');}</script></body>

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.