Such. There's a problem here, for example, in a line in the code, I would like to use a declared variable x, the result of typing or spelling errors, the variable is written y, the result is equivalent to "implicit" declared a variable y, in the actual programming process, this error is sometimes more difficult to find.
In addition, today, through the introduction of colleagues, to understand this "implicit declaration" in the outside of a problem.
When you make this "implicit" declaration within the current context, the JavaScript engine first looks in the current context to see if it has previously declared the variable, if not, to look in the context of the previous level, and if it has not been found, will finally declare the variable on the window!
Like what:
Copy Code code 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 in that layer is modified without generating a new variable on the window. (This bug is also very annoying, especially the encapsulation of more complex code)
Like what:
Copy Code code as follows:
var x = "window.x";
function A () {
var x = "A ' s X";
var B = function () {
var c = function () {
No var!
x = "C ' 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);
Here are the following layers: window, func A, func B, func C has been nested hierarchically. Window->a->b->c
In Windows and a, there are defined variables that are not defined in X,b, and an X is ' implicitly ' declared in C, which eventually modifies the value of a variable.
Keep in mind that in JavaScript, declare a variable, and be sure to add the preceding var.