Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ JavaScript closures and the scope chain     - MongoDB study notes - polymerization (Database)

- Installation and Configuration rsync server under CentOS 6.3 (Server)

- Oracle SQL statement tracking (Database)

- Protect against network attacks using Linux system firewall (Linux)

- Oracle LONG RAW BLOB CLOB type of presentation (Database)

- CentOS / Linux kernel upgrade (Linux)

- Ubuntu configuration SVN and http mode access (Server)

- CentOS 6.7 compile and install LAMP (Server)

- Oracle to create an external table (Database)

- Summarize small problems encountered in the use Lua (Programming)

- MySQL optimization resulting order by using filesort (Database)

- Use window.name + iframe cross-domain access to data Detailed (Programming)

- How to add any of a Linux distribution beautiful fonts (Linux)

- Use Python automatically cleared Android Engineering excess resources (Programming)

- The Java development environment to build under Ubuntu 14.04 (Linux)

- Linux ban single-user mode to enhance system security (Linux)

- Installation salt-minion on RHEL5 (Linux)

- Ubuntu deployed under regular tasks with crontab (Linux)

- CMake Quick Start Tutorial (Linux)

- Install Java on RHEL6 (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.
- Linux ps command (Linux)
- Usage Linux device tree (Programming)
- Nginx + uWSGI + Django + Python Application Architecture Deployment (Server)
- df show disk space usage (Linux)
- Linux System Getting Started Tutorial: Installing Brother printer in Linux (Linux)
- Docker study notes (Server)
- CentOS7 Kubernetes used on container management (Server)
- Oracle table space is too large processing time (Database)
- How to force Linux users to change the initial password the first time you log in (Linux)
- MySQL my.cnf sql_mode schema modifications (Database)
- Struts2 : combobox label use (Programming)
- How a lot of blocking malicious IP address in Linux (Linux)
- Install the latest Pinta graphics editing software on Ubuntu 14.04 (Linux)
- OpenGL ES 3.0 vertex buffer (Programming)
- ElasticSearch basic usage and cluster structures (Server)
- Installation and Configuration ISC DHCP server on Debian Linux (Server)
- AngularJS notes --- Data Binding (Programming)
- Use JMS listener Oracle AQ, trigger the execution of Java programs in the database changes (Database)
- Ubuntu modify locale problem solving (Linux)
- Manually generate AWR reports (Database)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.