Scope of JS Supplement

Source: Internet
Author: User

Any programming language has a concept of scope

To put it simply, scopes are the accessible scope of variables and functions, that is, scope controls the visibility and life cycle of variables and functions.

In JavaScript, the scope of a variable has both global scope and local scope.

1 scope (global scope)

Objects that can be accessed anywhere in the code have global scope, and in general there are several scenarios where you have global scope:

(1) The outermost function and the variables defined outside the outermost function have global scope

var name= "Yuan";    function foo () {        var age=23;        function inner () {            console.log (age);        }        Inner ();    }    Console.log (name);    Yuan    //console.log (age);   Uncaught referenceerror:age is not defined    foo ();    inner ();              Uncaught Referenceerror:inner is not defined

(2) All variables that are directly assigned to the last definition are automatically declared to have global scope, for example:

    var name= "Yuan";    function foo () {        age=23;        var sex= "male"    }    foo ();    Console.log (age);    console.log (sex);   Sex is not defined

The variable blog has a global scope, and sex cannot be accessed outside the function.

(3) All Window object properties have global scope

In general, the built-in properties of the Window object all have global scopes, such as Window.alert (), window.location, Window.top, and so on.

2 scope (local scope)

In contrast to the global scope, local scopes are generally accessible only within a fixed code fragment, the most common of which is inside the function, and in some places it can be seen that this scope has been used as a function scope.

As in Example 1, age and inner have only local scopes. (JS If, for does not have its own scope)

Scope Chain (scope Chain)

In JavaScript, functions are objects, and in fact, everything in JavaScript is an object. function objects, like other objects, have properties that can be accessed through code and a series of internal properties that are accessible only by the JavaScript engine. One of the internal properties is [[Scope]], defined by the ECMA-262 Standard third edition, which contains a collection of objects in the scope of the function being created, called the scope chain of the function, which determines which data can be accessed by the function.

Sample Demo

Please have a try:

-----********************** case 1*********************************var s=12;    function f () {        console.log (s);         var s=12;          If S=12        console.log (s)    }    f ();//-----********************** Example 2*********************************var s =10;function foo () {  console.log (s);  var s=5;  Console.log (s);  function S () {console.log ("OK")}//functions are defined or declared to be completed at lexical analysis, and no action is taken at execution  Console.log (s);} Foo ();//-----*********************** Example 3********************************function Bar (age) {        console.log (age);        var age = 99;
var sex= ' male '; Console.log (age); Function age () {
Alert (123) }; Console.log (age);
return 100;} Result=bar (5);//-----********************************************************
Results analysis

I believe you will have unexpected results, and then we will analyze the whole process with the most complex example 3.

When a function is created, its scope chain is populated with data objects that can be accessed by creating the scope of this function. When the function bar is created, it fills a global object in its scope chain, which contains all the global variables, as shown in:

Parsing to a function call, bar (5), generates an object of the active object that contains all the local variables, named arguments, parameter sets, and this of the function, which are then pushed into the front of the scope chain, and the active objects are destroyed when the run-time context is destroyed. The new scope chain is as follows:

Process parsing:

function bar (age) {Console.log (age);        var age = 99;        var sex= "male";        Console.log (age);        Function age () {alert (123);        } ;        Console.log (age); return 100;}    Result=bar (5); a lexical analysis process (involving parameters, local variable declarations, function declaration expressions): 1-1 , analysis parameters, have a parameter, form a  AO.age=undefine;    1-2 , receiving parameters  AO.age=5; 1-3 , analysis variable declaration, there is a  var age,  discovery  AO  there is a  ao.age , do not do any processing 1-4, analysis variable declaration, there is a  var    Sex, forming a  AO.sex=undefine;  1-5, analysis function declaration, there is a  function age () {}  declaration, then the original  age  cover into  ao.age=function () {}; second execution process:   2-1 , when performing the first  console.log  , the current  AO.age  is a function, so the output of a function    2-2 , This sentence  var age=99;  is not  AO.age  property assignment,  ao.age=99  So the age of the second output is  99;    2-3            The third output is  99,  because there are no statements that change the  age  value in the middle.             Note: Execution phase: function Age () {alert (123)           } ; Without doing anything, copying the execution statements to the age is done in lexical analysis, that is, before running.

Scope of JS Supplement

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.