In JavaScript, var is used to declare variables, but this syntax is not strictly required. Many times, we can directly use a variable without using var to declare it.
The code copy is as follows:
var x = "XX";
y ="xxx";
And so on. There is a problem with this. For example, in a line in the code, I want to use a declared variable x. As a result, due to typing or spelling errors, this variable is written as y. The result is equivalent to an "implicit" declaration of a variable y. In actual programming, this error is sometimes difficult to detect.
When you make this "implicit" declaration in the current context, the JavaScript engine will first look for whether this variable has been declared before in the current context. If not, then search in the previous level of context. If it has not been found, it will finally declare this variable on the window!
for example:
The 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 such an "implicit" definition of variable, the variable of that layer will be modified without generating a new variable on the window. (This kind of bug is quite annoying, especially the encapsulated more complex code)
for example:
The 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 bx:" + x); c(); alert("after c run, the bx:" + x); }; alert("ax is:" + x); b(); alert("after b function run, the ax is:" + x); }; alert("before a run, window.x:" + x); a(); alert("after a run, window.x:" + x);There are the following layers here: window, func a, func b, func c is always nested at levels. window->a->b->c
Both window and a define variable x, and b is not defined. An x is declared in c, which eventually modifies the value of the variable a.
Remember, in JavaScript, declare variables, and you must add var before it.