In JavaScript, VaR is used to declare a variable, but this syntax is not strictly required. If you modify it many times, you can directly use a variable instead of using VAR to declare it.
VaR x = "XX ";
Y = "XXX ";
And so on. This has a problem. For example, in a certain line of code, I want to use a declared variable X. As a result, the variable is written as y due to incorrect typing or spelling, the result is equivalent to "implicit" declaring a variable Y. In actual programming, this error is sometimes hard to be found.
In addition, I learned from my colleagues today about other issues in this "implicit Declaration.
When you perform this "implicit" declaration in the current context, the JavaScript engine first checks whether the variable has been declared in the current context. If not, search in the context of the upper level. If it is not found, the variable will be declared in the window!
For example:
Window. Y = "hello ";
Function func (){
Y = "Oh, no !!! ";
}
Func ();
Alert (window. Y); // # => display "Oh, no !!! "
When any layer in the context contains variables defined by "implicit", the variable at this layer will be modified without generating a new variable on the window. (This bug is also annoying, especially the encapsulated complicated code)
For example:
VaR x = "window. X ";
Function (){
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. X is:" + x );
};
Alert ("before a run, window. X:" + x );
A ();
Alert ("after a run, window. X:" + x );
There are the following layers: window, func A, func B, and func are always hierarchical nesting. Window-> A-> B-> C
In Windows and A, both the defined variable X and B do not define the variable. In C, the 'implicit 'declares an X, and the X finally modifies the value of the variable.
Remember to add var before declaring a variable in JavaScript.