In JavaScript, VAR is used to declare variables, but this syntax is not strictly required, and in many changes, we can directly use a variable without var to declare it.
[JavaScript]View Plaincopyprint?
- var x = "XX";
- y ="xxx";
Such. There is a problem, for example, in a line in the code, I want to use a declared variable x, the result of typing or spelling errors, this variable is written as Y, the result is equivalent to "implicitly" declared a variable y, in the actual programming process, the error is sometimes more difficult to find.
When you make this "implicit" declaration within the current context, the JavaScript engine will first look in the current context to see if the variable was previously declared, and if not, go to the upper-level context and look for it, if it has not been found, the variable will be declared on the window at the end!
Like what:
Copy CodeThe code is as follows:
Window. y = "Hello";
function func () {
y = "OH, NO!!!";
}
Func ();
alert (WINDOW.Y); #=> display "OH, NO!!!"
When any layer in the context has this "implicitly" defined variable, the variable of that layer is modified without generating a new variable on the window. (This bug is also annoying, especially with the more complex code of encapsulation)
Like what:
Copy CodeThe code is as follows:
var x = "window.x";
function A () {
var x = "A ' s X";
var B = function () {
var c = function () {
No var!
x = "C ' s x:";
};
Alert ("Before C run,the b.x:" + x);
C ();
Alert ("After C run, the b.x:" + x);
};
Alert ("a.x is:" + x);
b ();
Alert ("after-B function runed, the a.x is:" + x);
};
Alert ("Before a run, window.x:" + x);
A ();
Alert ("After a run, window.x:" + x);
This has the following layers: window, func A, Func B, and Func C have been nested hierarchically. Window->a->b->c
In window and a, there are defined variables in the variable x,b that are not defined in C, ' implicitly ' declares an X, which eventually modifies the value of the A variable.
Keep in mind that in JavaScript, declaring variables must be preceded by Var.
Why do I encourage the addition of the Var keyword when JavaScript declares variables