The scope and scope chain of JavaScript

Source: Internet
Author: User
Tags variable scope

Today is the first day of 2016, we have to set sail to embark on a new journey. This article describes several concepts that are important in javascript: scope and scope chains, and related knowledge points.

Let's start with a discussion of the behavior of variables and scopes.

Variable scope

In JavaScript, a variable has a global variable and a local variable, and a block that can define the scope of a variable has only a function. An interesting feature related to local variables, which has to be discussed here--variable elevation.

Variable Promotion

What is a variable promoted to?

JavaScript variable declarations are promoted to the top of their function, and initialization is still in place. The JavaScript engine does not rewrite the code: each time the function is called, the declaration is lifted again.

    var name = ‘Jog‘; //全局变量    function prison() {        console.log(a); //输出undefined        var a = 1;//局部变量        console.log(a); //输出1        console.log(name); //输出Jog    }    prison();
    var name = ‘Jog‘;    function prison() {        console.log(name); //输出undefined        var name = ‘Hans‘;    }    prison();

The declaration of name here is promoted to the top of the function, where the variable is first started from the local scope and not found from the inside to the global scope.

Next we'll look at how JavaScript is lifted.

Variable promotion and execution Environment objects

Learning any language is like learning magic, at first it is confusing and awe-inspiring, but when the secret is uncovered it is almost disappointing, and JavaScript is not.

    • 1. Improve

When executing a block of code, the JavaScript engine interprets and then runs. The explanation process is mainly a few processes:

- (1) 声明该作用域内var变量- (2) 声明并初始化函数参数- (3) 声明并初始化声明式函数

See the explanation and execution mechanism of this series of notes JavaScript in detail

    • 2. Execution environment and execution environment objects

The execution Environment (execution context) is a concept that creates a new execution environment whenever a function is called.

The execution Environment defines the other data that a variable or function has access to, and determines their respective behavior.

- 1. 每个函数都有自己的执行环境。  当执行流进入一个函数时,执行环境就被推入一个环境栈中;函数执行之后,栈将其执行环境弹出,控制权返回到之前的执行环境。- 2. 如果变量在当前执行环境内可访问,则该变量在当前作用域内。- 3. JavaScript访问变量,其实就是访问该执行环境对象(变量对象)中的属性。- 4. 全局执行环境是最外围的一个执行环境。

execution Environment Objects -Each execution environment has a variable object corresponding to it, and all variables and functions defined in the execution environment are stored in the object.

    function fn(arg) {        var name = ‘Far‘;        inner();        function inner() {            console.log(‘inner‘);        }    }    fn(‘test‘);

When you call FN, the process is as follows

- 1. 创建一个空执行环境对象;- 2. 声明参数并赋值;{arg: 1}- 3. 声明局部变量;{arg:1, name: undefined}- 4. 预定义声明式函数;{arg:1, name: undefined, inner: function(){console.log(‘inner‘);}}- 5. 代码执行时,局部变量被赋值;{...name: ‘Far‘...}- 6. 执行环境对象上变量和函数属性保持不变,调用inner函数时,其内部会创建一个新的执行环境对象,依此可递归形成一条作用域链。
Scope and scope chain

When a variable can be accessed within a certain execution home, we call the variable within the current scope.

When executed in an execution environment, the code creates a scope chain for the variable object that corresponds to the execution environment .

The JavaScript engine looks for variables or functions within the scope of the execution Environment object, and the order is formed from the inside out to the global execution Environment object, which forms the scope chain .

The front end of the scope chain, which is always the variable object that corresponds to the current execution environment. If this execution environment is a function, its active object is used as a variable object. The next variable object in the scope chain is derived from the containing (external) execution environment of the current variable object, so that it continues to the global execution environment; The variable object of the global execution environment is always the last variable object in the scope chain.

    var age = 22;    var country = ‘China‘;    var name = ‘Java‘;    var job = ‘Web‘;    function outer() {        console.log(age);  //输出22        console.log(country); //输出undefined        var country = ‘Union‘;        var name = ‘Python‘;        inner();        function inner() {            console.log(name); //输出Python            console.log(job); //输出Web        }    }    outer();

The result of the code output is as follows:

- 1. outer函数执行时,首先在outer执行环境对象中查找age和country变量结果country存在但并未初始化赋值,输出undefined;而age未找到于是沿着作用域链向上到全局执行环境,在其变量对象中存在age属性,于是输出其值22.- 2. inner函数执行时创建自己的执行环境对象,其并没有定义name和job等变量,于是沿着作用域链向上到达outer函数的执行环境,在其变量对象中存在name于是输出其值Python;而未找到job于是继续向上直到全局执行环境,找到并输出其值,结束;若依然未找到,则会报错,停止运行。

Note: Function parameters are also treated as variables, so their access rules are the same as normal variables.

Extend the scope chain

Some statements can temporarily add a variable object to the front of the scope chain, and the variable object is removed after the code execution ends. Common example:

    • Try-catch statement; The catch statement creates a new variable object that contains the declaration of the thrown error object.
    • With statement, the WITH statement creates a variable object that contains all the properties and methods of the statement receiving object.
    function getAttr(data) {        var obj = data;        with(obj) {            var o = location;        }        console.log(o);    }    getAttr(window);

The above with statement receives the Window object, which creates a variable object that contains all the properties and methods of the Window object, so that the location variable can be accessed directly in its execution, that is, the normal window.location.

It is strongly recommended that you do not use the WITH statement.

This note describes the JavaScript execution environment and execution environment objects, variable objects, scopes and scope chains, taking four hours, and many deficiencies to be added later.

The scope and scope chain of JavaScript

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.