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.
- 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