JS Compilation and execution order

Source: Internet
Author: User

JS is a piece of execution (in the <script> tag to split), before executing each paragraph, there is a "precompiled", pre-compiled to do the job is: declare all var variables (initially undefined), parse the definition function statement.

There is also a classic difference between a = 1 and var a = 1 under the window scope:

A = 1 equals WINDOW.A = 1, which dynamically adds a member to the window;
var a = 1 is the declaration of a under the current scope (that is, window), which is valid across the scope.

In other words, the difference is that var a = 1 is more than a = 1 of a declared behavior.

Let's look at a few more examples:

1.

Alert (t);
Alert (' OK ');
t = 2;

T is not declared, execution error.

2.

Alert (t);
Alert (' OK ');
var t = 2;

Eject undefined and OK. When precompiled, the variable T is declared, and when it executes to the code of Alert (t), T is not yet assigned, so it pops up undefined.

3.

A ();
function A () {}
Alert (' OK ');

Popup OK. At the time of precompilation, the definition function A () {} was parsed and executed successfully.

4.

A ();
var a = function () {};
Alert (' OK ');

A is not a function, perform an error. When precompiled, the variable a = undefined is declared, and a is also equal to undefined, not a function when executing to a (), so executing a () will cause an error.

5.

<script type= "Text/javascript" >
A ();
Alert (' first block ');
</script>
<script type= "Text/javascript" >
Alert (' second block ');
</script>

6.

    1. Eject second block. Because JS is a period of execution, the first paragraph executes to a () when the error, the whole first paragraph will not be executed, the second paragraph normal execution.

Firefox also has a little trick:

If there is no error in the above example, enter About:config, search strict, look at javascript.options.strict, if false to change him to true.

JS Compilation and execution order

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.