And so on. There is a problem. For example, in a certain line of the code, I want to use a declared variable x. As a result, due to typing or spelling errors, the variable is written as y. The result is equivalent to an "implicit" declaration of a variable. y, in the actual programming process, this kind of error is sometimes difficult to find.
In addition, today through the introduction of a colleague, I learned about another problem in this "implicit declaration".
When you make this "implicit" declaration in the current context, the JavaScript engine will first look in the current context to see if this variable has been declared before. If not, then go to the previous context to find it. If It has not been found and will finally declare this variable on 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 has such an "implicitly" defined variable, the variable in that layer will be modified instead of Generate a new variable on window. (This kind of bug is also quite annoying, especially when encapsulating more complex code)
For example:
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);
There are the following layers: window, func a, func b, func c are always hierarchically nested. window->a->b->c
Both window and a have defined variable The value of a variable.
Remember, in JavaScript, when declaring a variable, you must add var before it.