Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ JavaScript closures and the scope chain     - C ++ complex class of operator overloading (Programming)

- Installation and management of Linux applications (Linux)

- Hibernate Search 5.5 in the search results sorted (Linux)

- Linux Platform Oracle 11g Single Instance Installation Deployment Configuration Quick Reference (Database)

- Modular JavaScript (Programming)

- Use scripts easily install the latest Linux kernel in Ubuntu (Linux)

- Upgrading from Fedora 20 to 21 (Linux)

- Oracle 11g contraction table space error ORA-03297: file contains used data beyondrequested RESIZE value (Database)

- SecureCRT use the configuration detailed tutorial (Linux)

- Java gets the current system time System.currentTimeMillis () (Programming)

- EXP-00091: Exporting questionable statistics Processing Method (Database)

- Debian users to install FFmpeg 2.2.2 (Linux)

- How to configure a server in a MySQL Cluster (Database)

- Magical Virtualbox under Ubuntu (Linux)

- Android Studio quick overview of Gradle (Programming)

- C ++ stderr / stdout redirected to a file (Programming)

- Linux system Iptables Firewall User Manual (Linux)

- Linux System Getting Started Learning: hard disk partition, and to deal with traps (Linux)

- Proper use Core Data multithreaded 3 ways (Programming)

- Linux installed Cisco Packet Tracer (Linux)

  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.
- Installation and Configuration Munin monitoring server on Linux (Server)
- Oracle Client Easy Connection error ORA-12154, TNS-03505 (Database)
- You must ask yourself four questions before deploying Docker (Server)
- Ubuntu treated with cue file to ape and wav files automatically track points (Linux)
- C # using the HttpClient Note: Preheat the long connection (Programming)
- Let the router be your security barrier against external attack (Linux)
- Ubuntu and Archlinux install Notepadqq 0.50.2 (Linux)
- Cancel Root Command History under Linux (Linux)
- CentOS 6.5 makes the LAN http source (Linux)
- The sublime into IDE (Linux)
- Linux SVN installation and configuration graphic tutorials (Server)
- Single-node Hadoop environment to build (Server)
- VPS xen openvz kvm (Server)
- CentOS7 install MySQL 5.5 (Database)
- Raspberry Pi configuration wireless hotspot (Linux)
- The Java utility, JavaMail (Programming)
- Installation Yarock 1.1.4 Music Player in Ubuntu (Linux)
- Configuring a Linux operating system security management services Explain (Linux)
- Oracle Database import and export combat (Database)
- Copy and paste in Linux terminal and Vim (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.