Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ JavaScript closures and the scope chain     - How to use Evernote in the Linux command line (Linux)

- Linux package manager - yum (Linux)

- Android and OpenCV2.4.4 build an image processing framework (2013 edition) (Linux)

- The callback function used in C ++ (Programming)

- Android judgment toward camera pictures (Programming)

- Linux Basics Tutorial: Combining awk delete data before the specified date hdfs (Linux)

- Remote installation of Net-SNMP whole process (Linux)

- Analysis of native Java keywords (Programming)

- Ubuntu: To install chat client Chatty 0.6.1 (Linux)

- Ruby and Python simple comparison (Programming)

- The Java way to stop a thread of execution (Programming)

- Oracle inline view updates problems encountered (Database)

- CentOS 6 kernel upgrade to Kernel 3.x (Linux)

- CentOS7 method to upgrade the kernel to 3.18 (Linux)

- How to Install Redis server on CentOS 7 (Server)

- The Linux-based security settings Ipchains Firewall (Linux)

- How to avoid two Chrome icon appears in ELementary OS Freya (Linux)

- Java call by value and by reference (Programming)

- On Android running ClojureScript (Linux)

- Java polymorphic methods inside constructors complete analysis (Programming)

  JavaScript closures and the scope chain
  Add Date : 2017-09-03      
  To understand closures, JavaScript should first understand the scope and the scope chain.

JavaScript has a feature called "statement in advance (hoisting)", that is, all variables declared in the JavaScript function (but does not involve the assignment) are "early" to the top of the body of the function, "the statement ahead" this operation is when the "pre-compiled" JavaScript engine conducted before the code starts running, look at the following examples:

var name = "YY";
function getName () {
    console.log (name); // output undefine, instead of "YY"
    var name = "Crucify";
    console.log (name); // output "Crucify"
First, local variables are defined the same as a global variable name of the variable in the function body inside a local variable obscures the global variable of the same name, then advance the top to the body of the function in the function inside a variable name is declared but not assigned, so this when a name is only declared but not initialized variable, we know only variable is declared but not initialized then its value is undefine, so undefine the first line of print, the next line is the variable name assignment, so the first two lines printed output is what we expect.

When a function is called, it creates an execution environment and the appropriate scope chain.

Execution Environment (execution context) defines the additional data variables or functions have access to, determine their own behavior. Each function has its own execution environment. When the execution stream enters a function, a function of the environment will be pushed into a stack environment. And after the function is executed, the stack will pop up its environment, before returning control to the execution environment. When the code is executed in an environment creates a scope chain variable object (scope chain). The scope chain use is to ensure the implementation of the right to access environmental ordered access to all variables and functions.

The scope chain is essentially a pointer to the object list of variables, but it does not actually contain a reference to the variable object. JavaScript When you need to find the value of the variable x time (this process is called "variable parsing" (variable resolution)), he will begin to look for an object from the list until the last among the first object, if an object has a name for the x property, it will direct consumption value of this property. If no one objects containing attribute x on the scope chain, then that does not exist on the scope of the code of x, and eventually throw a reference error exception.

The so-called "variable object pointer list" well understood. Topmost in JavaScript code (that is, the code is not included in any function definition), is a global scope chain objects. In the body of the function does not contain nested, there is the scope chain of two objects, the first object-defined function parameters and local variables, and the second is the global object. In a nested function of the body, then at least three objects on the scope chain, look at the following example:

var name = "YY";
function getName () {
    var name = "Crucify";
    function f () {
        return name;
    return f ();
There are function f () scope chain of three objects, the first is to define the function f () object parameters and local variables, and the second is to define the function getName () object parameters and local variables, and the third is global object.

Each environment can search up the scope chain, to check variable and function names, but not through any environment down search scope chain into another execution environment, that the function f () function can search for up getName () and global object attributes, but can not search the global object down getName () and f () in value.

Created closures common way is to create an internal function to another function. Closure refers to a function has access to another function scope variables.

Generally speaking, when the function completes, the local active object is destroyed, stored in the memory only global scope (global variable object execution environment). However, the situation is different closures, because the function definition inside another function will contain functions (ie external function) of the active object added to its scope chain, with reference to the following code:

function createComparisonFunction (propertyName) {
    return function (object1, object2) {
        var value1 = object1 [propertyName];
        var value2 = object2 [propertyName];
        if (value1 < value2) {
            return -1;
        } Else if (value1> value2) {
            return 1;
        } Else {
            return 0;
When the following code executes, the scope chain containing a function and internal anonymous function as shown:

var compare = createComparisonFunction ( "name");
var result = compare ({name: "Nicholas"}, {name: "Greg"});

When createComparisonFunction () function after the implementation of its activities the object will not be destroyed because the anonymous function scope chain is still in reference to the active object. Until the anonymous function is destroyed, createComparisonFunction () event object will be destroyed:

compare = null; // release the reference to the anonymous function (to free up memory)
Since the closure will carry a scope containing function, and therefore will take up more memory than any other function. Excessive use of closures may cause excessive memory footprint, so when it is absolutely necessary to consider the use of closures.

This configuration mechanism of the scope chain leads to a notable side effect of the closure can only get the last value of any variable that contains the function. Because closures saved the entire variable object rather than to a particular variable:

function createFunctions () {
    var result = new Array ();
    for (var i = 0; i < 10; i ++) {
        result [i] = function () {
            return i;
    return result;
This function returns an array of functions, and each function returns 10.

Use this object closure may also cause some problems. We know, this object is a run-time execution environment based on the function of binding, and the execution environment of the anonymous function is global, so it usually points to this target window (function execution environment by changing the call () or apply () of case, this would point to other objects), look at the following example:

var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function () {
        return function () {
            return this.name;
alert (object.getNameFunc () ()); // "The Window" (in non-strict mode)
The scope of this external objects stored in a closure can have access to the variable, you can make the closure to access the object, as shown below:

var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function () {
        var that = this;
        return function () {
            return that.name;
alert (object.getNameFunc () ()); // "My Object"
arguments have the same problem. If you want to access the arguments object scope, you must save a reference to the object to another variable closure can access.
- Use Visual Studio 2015 to develop Android program (Programming)
- Linux kernel IPv6 protocol closed manner (Linux)
- CentOS6 5 Configure SSH password Free (Linux)
- CentOS7 compile and install Tengine + PHP + MariaDB notes (Server)
- Build a super simple "hardware" firewall router (Linux)
- Ubuntu prevent arp attacks (Linux)
- DVD production using CentOS installation source within the company Yum (Linux)
- CentOS 6.x Basic System Optimization after installation (Linux)
- Ubuntu PPA install SMPlayer 14.9 (Linux)
- On the PC goes heavy security watch your startup items (Linux)
- Oracle 12CIN-memory in table spaces (Database)
- Oracle LONG RAW BLOB CLOB type of presentation (Database)
- Java Foundation - Variables and data types (Programming)
- Python 3.5 await / async (Programming)
- Sublime Text Add instructions to insert the current time zone (Linux)
- Linux operation and maintenance engineers face questions Intermediate (Linux)
- C language macro definition #define Usage (Programming)
- Ubuntu server 8.04 Firewall Guide (Linux)
- Oracle can not change the tablespace to backup mode in non-archive mode (Database)
- Standardized UNIX command-line tool (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.