JavaScript's variable pre-parsing feature

Source: Internet
Author: User

JavaScript is an interpreted language, but it is not only in the run-time from the last sentence to parse it? In fact or some kind of phenomenon proves that this is not the case, through the "JavaScript authoritative guide" and online related information learned that JavaScript has "pre-analytic" behavior. It is important to understand this feature, or you may encounter a lot of unresolved problems in actual development, or even cause bugs in the program. In order to resolve this phenomenon, but also as a study of their own summary, this article gradually guide you to understand the JavaScript "pre-analysis", if my opinion is wrong, but also to correct. Chizhou-Sheng Crafts

Let's first look at an example:

var lastName = "Gonn";(function Displaylastname () {Console.log (lastName), var lastName = "Zeng"; Console.log (LastName);}) Who can guess what the result is?

The feeling should be output gonn and then output Zeng.

But the result is undefined Zeng. Why is it?

JavaScript performs a "pre-parsing" operation before it executes: it first creates an active object under the current execution environment and sets those variables declared with Var as the properties of the active object, but at this point the assignment of these variables is undefined. The functions defined by the function are also added as properties of the active object, and their values are the function definitions.

In interpreting the execution phase, when a variable needs to be parsed, it is first looked up from the active object of 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 found by the scope chain. Encountered var a = ... Such a statement assigns a value to the corresponding variable (note: The assignment of the variable is done during the interpretation execution phase, and if the variable is used before it, its value will be undefined).

That is, before the interpretation of the implementation, do a pre-parse, the VAR variable is assigned to undefined. When the local variable has VAR, then LastName exists as a local variable inside the function. If Var lastname= is changed to lastname= in the above function, the result will be different. At this point, the pre-parsing will not be used as a local variable, assigned to a value of undefined.

Here are some more examples to illustrate.

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

The result is: undefined. Since in the explanation to var arg1 = 20; The value of Arg1 was printed before this sentence, and arg1 is not yet assigned.

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

Result: Handle is not a function. Since the execution of handle () does not give handle an assignment – a function definition. If you change to:

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

The dialog box will pop up under IE because it will handle Var ... This sentence is interpreted as a function definition, and the function definition should be evaluated at precompiled time, so it can be executed. However, in the FF, it is still only interpreted as a variable declaration, knowing that the execution of this sentence is not assigned to a value.

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

The exception to Try/catch is the following code:

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

The above code in IE, chrome running results are undefined, undefined and fuction () {alert (2), and in Firefox the result is undefined, undefined and "fun undefined" error. It's not clear what Firefox is doing with Try/catch's "pre-parsing".

1. If JavaScript is only parsed by the runtime from the top down, it is understandable that the following code will work correctly, because we define the function before calling it.

function ShowMsg () {    alert (' This is message ');} ShowMsg (); This is message

2. We also know that functions can be defined after the code is called, and the following code will work as expected. It seems that showmsg () is not defined when calling ShowMsg (), but working correctly indicates that JavaScript is "pre-parsed".

ShowMsg (); This is Messagefunction showmsg () {    alert (' This is message ');}

3. Above is an example of a function, the following is an example of a common variable. The following example run will pop up undefined, indicating that the first sentence of the MSG is already defined, just not initialized, and it is associated with var msg; Alert (msg); it's the same. If you comment out the second sentence below, the "msg undefined" error is reported. This also indicates that JavaScript is "pre-parsed".

Alert (msg); Undefinedvar msg= ' This is message ';

4. Take another example to deepen the "pre-parsing" impression of JavaScript. The following code you will see two times the pop-up dialog box is displayed for this is message 2, why is it this way? In fact, the following one defines two functions of the same name, followed by ShowMsg () overwrite the previously defined (in JavaScript, the same name variable will have a overwrite problem), is equal to the first showmsg () scrapped. Why does the second invocation of ShowMsg () not call the message 1 function defined above it? This proves once again that JavaScript has "pre-parsed" behavior.

ShowMsg (); This is a message 2function showmsg () {    alert (' This is Message 1 ');} ShowMsg (); This is a message 2function showmsg () {    alert (' This is Message 2 ');}

5. JavaScript "Pre-parsing" is the pre-parsing of variables or functions into the environment in which they can be called (Variable runtime environments). The following code looks like the definition of MSG before alert (msg), but the program runs or reports "msg undefined" error because the variable defined in the function is a private variable of the function and cannot be called directly outside, which indicates that JavaScript "pre-parsing" Not all defined variables are parsed uniformly into a global object, such as window.

function ShowMsg () {    var msg= ' This is message ';} Alert (msg); MSG Not defined

6. JavaScript "Pre-parsing" is segmented, accurate is the sub-<script> block. The following code appears in two script blocks on the same page, and defines three functions with the same name. The result of the program operation indicates that the second script block's showmsg () does not overwrite the first two showmsg (), while the second showmsg () of the first script block overrides the ShowMsg ().

<body><script type= "Text/javascript" >showmsg (); This is a 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>

JavaScript's variable pre-parsing feature

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.