Use Var to define the precompiled effect of variables in JavaScript

Source: Internet
Author: User

First of all, the JavaScript syntax is very flexible, the price of flexibility is easy to lead to irregular coding and a variety of unexpected running results. ECMAScript 5 introduces the strict mode (strict mode), and in the future we'd better write JavaScript code using "use strict" to standardize our JavaScript code. The following test code is not based on strict mode.

alert (a); var a;//declared not assigned alert (b);//Undeclared variable

The result of the execution is:a print undefined,b error. This shows:var A; The execution of this statement precedes alert (a) .

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

Execution Result: print undefinedFirst, then print 1. Actually just put the declaration forward, but the assignment statement still doesn't change position

alert (a); a = 1;

Execution Result: code error. Visible without the var keyword, the declaration of a variable is not advanced, and there is no "precompiled" process.

function TestClass () {    //does not use the var keyword to define the global variable    val = 1;    Alert (val);    Global variables are stored in the Window object,    alert (window.val);};/ /Call TestClass Constructor test = new TestClass ();//Verify again is a global variable alert (val);

Without Var, a global variable is defined and placed in the Window object.


function TestClass () {    val = 1;    Alert (val);//1    alert (window.val);//undefined        var val = ten;    Alert (val);//10    alert (window.val);//undefined}var test = new TestClass (); alert (val);//js error, variable is defined

This shows: using var to define the variable, the variable declaration will be advanced, but the assignment will not advance.

Use Var to define the precompiled effect of variables in JavaScript

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.