Javascript var variable implicit declaration method _javascript Skill

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.