In JavaScript, var is used to declare variables, but this syntax is not strictly required. In many cases, we can use a variable directly without declaring it with var.
And so on. There is a problem. For example, in a certain line of 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 "implicitly" declaring 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 search in the current context to see if this variable has been declared before. If not, then search in the previous context. If It has not been found and 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 "implicitly" defined variable, then the variable in that layer will is modified without generating a new variable on the window. (This kind of bug is also 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 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 variables x. The variable is not defined in b, and one is 'implicitly' declared in c. x, which ultimately modifies the value of the a variable.
Remember, in JavaScript, when declaring a variable, you must add var before it.
The above is the detailed content of Detailed explanation of implicit declaration method of Javascript var variable. For more information, please follow other related articles on the PHP Chinese website!