Use var in javascript to define the effect of variable pre-Compilation
Note: The javascript syntax is very flexible. The flexible cost is that it can easily lead to nonstandard coding and unexpected running results. ECMAScript 5 introduces strict mode. In the future, we 'd better use "use strict" to compile javascript code. The following test code is not based on the strict mode.
Alert (a); var a; // declared unassigned alert (B); // undeclared variable
The execution result is: a prints undefined and B reports an error. This statement is executed before alert (.
alert(c);var c = 1;alert(c);
Execution result: Print undefined first, and then print 1. In fact, the declaration is in advance, but the assignment statement still does not change the position.
alert(a);a = 1;
Execution result: the code returns an error. It can be seen that there is no var keyword, the variable declaration will not be in advance, and there is no "pre-compilation" process.
Function TestClass () {// If the var keyword is not used, the global variable val = 1; alert (val); // The global variable is stored in the window object alert (window. val) ;}; // call the TestClass constructor test = new TestClass (); // verify that it is a global variable alert (val );
Var is not used. In fact, a global variable is defined and will be placed in the window object.
Function TestClass () {val = 1; alert (val); // 1 alert (window. val); // undefined var val = 10; alert (val); // 10 alert (window. val); // undefined} var test = new TestClass (); alert (val); // js reports an error, the variable is defined
We can see that when using var to define a variable, the variable declaration will be made in advance, but the assignment will not be made in advance.