First of all, the JavaScript syntax is very flexible, the price of flexibility is easy to lead to irregular coding and a variety of unexpected running results. ECMAScript 5 introduces the strict mode (strict mode), and in the future we'd better write JavaScript code using "use strict" to standardize our JavaScript code. The following test code is not based on strict mode.
alert (a); var a;//declared not assigned alert (b);//Undeclared variable
The result of the execution is:a print undefined,b error. This shows:var A; The execution of this statement precedes alert (a) .
alert (c); var C = 1;alert (c);
Execution Result: print undefinedFirst, then print 1. Actually just put the declaration forward, but the assignment statement still doesn't change position
alert (a); a = 1;
Execution Result: code error. Visible without the var keyword, the declaration of a variable is not advanced, and there is no "precompiled" process.
function TestClass () { //does not use the var keyword to define the global variable val = 1; Alert (val); Global variables are stored in the Window object, alert (window.val);};/ /Call TestClass Constructor test = new TestClass ();//Verify again is a global variable alert (val);
Without Var, a global variable is defined and placed in the Window object.
function TestClass () { val = 1; Alert (val);//1 alert (window.val);//undefined var val = ten; Alert (val);//10 alert (window.val);//undefined}var test = new TestClass (); alert (val);//js error, variable is defined
This shows: using var to define the variable, the variable declaration will be advanced, but the assignment will not advance.
Use Var to define the precompiled effect of variables in JavaScript