The difference between a JavaScript declaration object with Var and no Var

Source: Internet
Author: User

When JavaScript declares variables

var AAA = 111;

And

AAA = 111;

Is it the same in two different ways?

Say less nonsense, first on the code.

var aaa = one; function test4 () {    var aaa = $;} Test4 (); Console.log (AAA);

What was the result? 11

This is a good understanding that the Var AAA declaration inside the function is an internal variable, and the result is the value of the first AAA.

Change as follows:

var abc = one; function test4 () {    =;} Test4 (); Console.log (ABC);

What was the result? 22

Further changes:

function test4 () {    var aaa = $;} Test4 (); Console.log (AAA);

What's the result? Run an Error! REFERENCEERROR:AAA is not defined!

Change:

function test4 () {    var aaa = $;} Test4 (); Console.log (TEST4.AAA);

Operation will not error, the output is undefined.

Conclusion 1: Variables declared within a function or object construct are private. cannot be accessed externally. Includes the object after the prototype inherits.

But if so:

function test4 () {    =;} Test4 (); Console.log (BBB);

The result is 33.

Point solution?

This is the difference between a declaration with Var and no var.

Conclusion 2: No Var is assigned within a function or construct, and the variable bbb is searched from within the function to the top layer. Declare a var BBB on the top level;

It's horrible. If a big project changes the value of BBB here, and does not add Var happens throughout the project global variable has a same name BBB is changed, no var is not only function in this function or object. It's hard to find out the mistake.

So write code must be cautious. Declaring variables to add can not be afraid of trouble. The result is completely different.

The difference between a JavaScript declaration object with Var and no 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.