Use var in javascript to define the effect of variable pre-Compilation

Source: Internet
Author: User

Use var in javascript to define the effect of variable pre-Compilation

Note: The javascript syntax is very flexible. The flexible cost is that it can easily lead to nonstandard coding and unexpected running results. ECMAScript 5 introduces strict mode. In the future, we 'd better use "use strict" to compile javascript code. The following test code is not based on the strict mode.

Alert (a); var a; // declared unassigned alert (B); // undeclared variable

The execution result is: a prints undefined and B reports an error. This statement is executed before alert (.

alert(c);var c = 1;alert(c);

Execution result: Print undefined first, and then print 1. In fact, the declaration is in advance, but the assignment statement still does not change the position.

alert(a);a = 1;

Execution result: the code returns an error. It can be seen that there is no var keyword, the variable declaration will not be in advance, and there is no "pre-compilation" process.

Function TestClass () {// If the var keyword is not used, the global variable val = 1; alert (val); // The global variable is stored in the window object alert (window. val) ;}; // call the TestClass constructor test = new TestClass (); // verify that it is a global variable alert (val );

Var is not used. In fact, a global variable is defined and will be placed in the window object.


Function TestClass () {val = 1; alert (val); // 1 alert (window. val); // undefined var val = 10; alert (val); // 10 alert (window. val); // undefined} var test = new TestClass (); alert (val); // js reports an error, the variable is defined

We can see that when using var to define a variable, the variable declaration will be made in advance, but the assignment will not be made in advance.

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.