What is the closure in JavaScript? What are the application scenarios?

Source: Internet
Author: User
Tags variable scope

Reply content:

See an example:
var Foo = ( function() {    var Secret = ' secret ';    //The function inside the "closure" can access the secret variable, while the secret variable is hidden from the outside    return {        Get_secret: function () {            //access to secret through defined interfaces            return Secret;        },        New_secret: function ( New_secret ) {            //Modify the secret by defining the interface            Secret = New_secret;        }    };} () );Foo.Get_secret (); //Get ' secret 'Foo.Secret; //Type error, Access cannotFoo.New_secret (' A new secret '); //Through the function interface, we access and modify the secret variableFoo.Get_secret (); //Get ' A new secret '
The content comes from: How does JavaScript closures work?
I was inspired by the explanation of the closures, and I took this opportunity to share the following ~

If You can ' t explain it for a six-year-old, you really don ' t understand it yourself.
There is a princess ...
A closure is a lexical scope created by a function that can be used freely outside the lexical environment after the variables created are referenced. ( https:// Secure.wikimedia.org/wi kipedia/zh/w/index.php?title=%e9%97%ad%e5%8c%85_%28%e8%ae%a1%e7%ae%97%e6%9c%ba%e7%a7%91%e5%ad%a6%29& VARIANT=ZH-CN

Closures are often used to create internal variables so that they cannot be arbitrarily modified externally and can be manipulated by a specified function interface. What is a closure package?

Closures (Closure) mean closed, a function object enclosing a local variable in an outer scope is called a closure. The closed variable has the same life cycle as the function object that encloses it.

what is a function object?

A function object is a function that is used as an object, where the object refers to the data that is manipulated by the programming language.

function object and Closure

A function object is not necessarily a closed packet.

In the C language, you can get a pointer to a function and call it indirectly through a pointer. This is the object in the C language (the function object is also an object). But the function object in C is not a closure-it cannot access the local variables of the outer scope.

In Javascript, each function has a scope chain associated with it. Each time a JavaScript function is called, a new object is created for it to hold the local variable, and the object is added to the scope chain. When the function returns, the object is deleted and the object is garbage collected. But if the function defines a nested function and stores it in a property somewhere, it means that an external reference points to the nested function. It is not treated as garbage collection, and the variable-bound object It points to is also not recycled.

Thus, the function object in JavaScript is a closure-it is possible to "close" the local variables of the outer scope.

What is an object?

Object oriented object refers to the element in the problem space (cat, dog) and its representation in the solution space (new Cat (); New Dog ()). An object is a combination of a procedure (function) and data.

objects and closures

The object is the process that is contained in the data as a method, and the closure is the data contained in the process in the form of an environment. The so-called "closure is the object of the poor", "object is the Poor's closure", that is, using one of these methods, you can achieve another way to achieve the function.

Application Scenarios

Security of variables within a protection function: such as iterators, generators.

Maintain variables in memory: If you cache data, Curry.


Personal summary, content according to "The Future of Code", "Rhino book", and "thinking in Java" collation.

Give an example to illustrate:
function Counter (start) {
var count = start;
return {
Increment:function () {
},//function increment

Get:function () {
return count;
}//function Get
}//function Counter

var foo = Counter (4);
Foo.increment ();
Foo.get (); 5

Here, the Counter function returns two closures, function increment, and function get. Both functions maintain a reference to the external scope Counter, so you can always access the variable count defined within this scope.

(Examples from articles: / http Bonsaiden.github.com/ja vascript-garden/ Although a lot of people answered, but still according to their own thinking logic and then tidy up the idea. The following answer is a look at the idea of the JavaScript Authority Guide.

-------------------long-text warning-------------------------

Let's start with the conclusion. Closures, in short, mean: The combination of the function object itself and the scope chain associated with the function

The definition above may not be understood, in order to elaborate on this concept, you need to first explain the scope-related concepts in JavaScript.

Variable Scope

A variable scope is a scope that a variable is visible in the source code after it is defined.

There are two types of variable scopes in javascript:

Global scope: Global variables have global scope and are visible throughout the JavaScript code

Local scope:
    • Variables defined in a function are local variables that have local scope and are fully visible inside their defined function body, and the parameters of the function are also counted as local variables of the function.
    • Local variables can overwrite global variables with the same name
    • Functions can be nested and each function has its own local scope environment.


/** * 全局变量,全局可见 */var globalVar = 'global Scope';var anotherGlobalVar = 'another global var'function fn(){     var localVar = 'local Scope';     var anotherGlobalVar = 'global override';     console.log( localVar );     console.log( globalVar );     console.log( anotherGlobalVar );}fn(); // 将输出:   'local Scope'  'globalScope' 'global override'console.log( localVar ); // 报错, localVar 不存在
The closure in JavaScript is really inseparable from its Scope Chain features.
Closures in JavaScript:
def foo () {
var a = 1;
def bar () {
A = a + 1;
alert (a);
return bar;

var closure = foo (); This time the bar () is returned and the variable a on its package is applied.
var closure2 = foo (); Another closure (instance) has also been generated here
Closure (); 2
Closure2 (); 2, bound to another copy of the variable A
Closure (); 3

For the normal Foo () method, the existence of the variable a inside it should disappear after the Foo () method has finished executing, but the Foo () method returns a new method bar (), which accesses the variable A of the Foo () method (JavaScript passes Scope Chain access to the Parent property), and the presence of the method bar () prolongs the existence of variable A, similar to closing the variable A at its own scope, as long as the method bar () does not fail, then variable a will always be accompanied by the method bar (), and The existence form of variable A and method bar () is called closure;

Applications for closures:
In my opinion, although the concept of closure is often heard, but the real application is not many, also did not see or think of more classic applications. In JavaScript, the most used, I'm afraid, is to use function as the first class, just like you can var a = new number (0); You can continuously pass a as a function parameter, you can also var f = new function (Arg1, arg2 ..., functionbody) [New function ("X", "Y", "return (x + y)/2")] To define the function, and then the F as a parameter in the function of the continuous transfer; But I generally do not let this function generate closures for delivery, but will pass a separate function to avoid writing more than they have forgotten which.

Implementation of JavaScript closures:
As it begins, the closure implementation in JavaScript is inseparable from the Scope Chain of JavaScript. First, there will always be an execute Context Stack in JavaScript execution (think of the JavaScript interpreter when it sees an alert (x), if there is no context how does he know what this x is?), execute Con The bottom of the text Stack must be globalcontext, and in every execution of the function beginsWill press into this stack a execution Context of this Function; And the composition of a execution Context is divided into three parts:
1. Variable object: The variable VARs within the storage method, the parameters passed in the method, functions defined within the function and so on (function expressions are not saved), Variable object can not be directly accessed at any time, of course, different JS engines provide access to the interface. The
2. Scope Chain: This function is used to find the value of the scope Chain, the scope Chain consists of Variable object + all Parent Scopes, Variable object will be placed in this The first of the scope Chain, which is why the variables within the function are first found;
3. Thisvalue, when the function is called, the This object is stored as a reference to the caller (caller) of the function;

For Variable object, there will be different definitions in different cases, such as global object at the time of the whole, and in the function is called Activation object;

It is because of the Scope Chain in execution context that JavaScript is able to make the method bar ()
The internal access to the variable A in method foo () will enable the method bar () to close the variable A to its own scope and not let him destroy it with the Foo () method execution complete;

ecma-262-3in detail. Chapter 1 ~ 6
/ http DMITRYSOSHNIKOV.COM/ECM ascript/chapter-1-execution-contexts/ The correct appellation for closures is first-class function with lexical scope.

The first-class function determines that functions can be defined inside another function and returned as return value.
Lexcial scope refers to: When a name is not a parameter or a local variable, the VM is bound from the local variable when the function defined by the function is run. If there is still no upward analogy (eventually all functions are defined at the global chunk runtime, it is finally bound from the global variable).

The environment model of the third chapter of Structure and interpretation of computer programming is the most accurate description of closures. Each function is defined with a bound environment, each of which has a created environment each time it is called. The bound environment of a function definition is the created environment when the function's outer function is called. Local variables in created environment, the closure variable is in bound environment. Say an application scenario.
Closures allow you to set private properties on an object and access private properties using the privileged (privileged) method.
  var Foo = function(){      var name = 'fooname';      var age = 12;      this.getName = function(){          return name;      };      this.getAge = function(){          return age;      };  };  var foo = new Foo();  foo.name;        //  => undefined  foo.age;         //  => undefined  foo.getName();   //  => 'fooname'  foo.getAge();    //  => 12
2015 Mid-Autumn Festival update:
Closures are caused by inconsistent function call stacks and scope chains.
I'll go back to my class and use the computer to describe it.

A closure is an entity that consists of a function and an external variable that it references.
Because the external variable is referenced, its life is extended. This brings a lot of interesting properties. It can be said that the external function is its biological mother, the closure function is its adoptive mother.
As stated in the MDN, closures associate a function with one (or more) variables, just like the objects in Java, the combination of behavior and attributes.
So, a closure is actually a function, but it's bound to a variable, which is a little more NB than a function that doesn't have a bound variable.

One of the more special cases is that n functions refer to the same external variable. This creates n closures, but because they share external variables, pay special attention to them. For example, one of the most common mistakes is to define closures in a loop, which refer to the loop variable. It seems as if they refer to different values, not actually, they refer to the same variable, whose value is the final value of the loop variable. Because JS is single-threaded, the closure function must be executed at the end of the loop, so the value of the variable they are referencing is the same.
The solution is to reconstruct the closures so that they each refer to different variables, each of which is initialized to a different value.

Also note that the outer variable referenced by the closure function is different from its local variable. It refers to an external variable that accompanies its entire life cycle, starting with its definition and accompanying the function to the end of its destruction. However, its local variables are only created when it is called, and the end of the call disappears.

Please criticize and correct me!
  • 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.