Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ JavaScript closures and the scope chain     - RedHat Linux source code package installation process (Linux)

- IBM Data Studio to create objects using ---- double quotes / sensitive issues and the table / column renaming (Database)

- lolcat: an output terminal rainbow effects in the Linux command-line tool (Linux)

- CentOS 6.6 running level (Linux)

- How to install Ubuntu applications Device 7 (Linux)

- Ubuntu configuration SVN and http mode access (Server)

- To disable the function by pressing Ctrl-Alt-Del to restart the system in RHEL / CentOS 5/6 (Linux)

- Retro terminal in Linux (Linux)

- RHEL 6.4 installed MySQL 5.6.27 (Database)

- Java development specifications summary (Programming)

- VMware virtual machine Ubuntu install arm-linux-gcc cross-compiler environment (Linux)

- Linux performance optimization features Tuned and ktune (Linux)

- MongoDB3.0.x version of the user authorization profile (stand-alone environment) (Database)

- Ubuntu 15.10 install the latest Arduino IDE 1.6.7 (Linux)

- Java collections series (Programming)

- The most common and most effective security settings under linux (Linux)

- Ubuntu install Oracle 10g process and problem solution (Linux)

- Java to achieve local fileCopy (Programming)

- CentOS 6.4 under PXE + Kickstart unattended operating system installation (Programming)

- awk pattern matching (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.
- How to configure security services under Linux (Linux)
- Oracle 11g user rights management study notes (Database)
- Secondary exponential smoothing prediction method implemented in Python (Programming)
- Linux simple commands (Linux)
- Ubuntu will be written in a command file, executable file, source command (Linux)
- 4 lvcreate example commonly used commands (Linux)
- Ubuntu system cp: omitting directory problem (Linux)
- Create your own YUM repository (Linux)
- Stunning exclamation point at the Linux command line (Linux)
- Build a super simple "hardware" firewall router (Linux)
- C ++ containers (Programming)
- GlusterFS distributed storage deployment (Server)
- grep command output highlighted word (Linux)
- Use SecureCRT to transfer files between Linux and Windows (Linux)
- SVN common commands (Linux)
- Lazarus IDE Start Basics Tutorial (Linux)
- Monitoring network traffic with Iptraf in Linux environment (Linux)
- How to install Perl modules from CPAN (Linux)
- New experience Budgie (Budgerigar) desktop environment (Linux)
- Free compiler install MySQL-5.6.14 (Database)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.