Scoping deep analysis in JavaScript

Source: Internet
Author: User

The scope of JS is functional division, not block, so JS scope is divided into global scope and local scope (function scope).
All variables that belong to the global scope are properties of the Window object
JS variable has a very important concept, scope chain

Look at an example to analyze

var str1 = ' global ';

function T1 () {
Console.log (STR1); <span style= "color: #222222;" >global</span>
Console.log (STR2); <span style= "color: #ff0000;" >uncaught REFERENCEERROR:STR2 is not defined</span>
str2 = ' local ';
}
T1 ();

Then analyze a

var str1 = ' global ';

function T1 () {
Console.log (STR1); Global
Console.log (STR2); Undefined
var str2 = ' local ';
}
T1 ();

Analysis: JS code from top to bottom, but JS code in the overall operation is divided into: Lexical analysis period and running period, that is, before the Top-down implementation, first has a "lexical analysis process." From the above results for example, the first analysis of the T1 function, analysis of the T1 var str2 local variables, but at the end of the function execution, because the STR2 value is undefined, in short, is to declare in advance but not assignment, (only for the value of VAR declaration) so the above code is equivalent to

var str1 = ' global ';
 
Function t1 () {
    var str2 = ';
    console.log (STR1);//global< br>     Console.log (STR2); Undefined
    str2 = ' local ';
}
T1 ();

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.