Let you learn JavaScript closures in minutes

Source: Internet
Author: User
Tags addchild closure definition

http://www.cnblogs.com/onepixel/p/5062456.html @ one Pixel

Closures, is an important concept in JavaScript, for beginners, closures are a particularly abstract concept, especially the ECMA specification to the definition, if there is no actual combat experience, you can not understand it from the definition. Therefore, this article does not have a large description of the concept of closures, directly on the dry goods, let you learn to close the pack minutes!

1 closures – The first experience of love

One of the first things I would do when contacting a new technology is to look for its demo code. For code farmers, code can sometimes understand a thing better than natural language. In fact, closures everywhere, such as: JQuery, Zepto's main code is contained in a large closure, so I will first write a simplest and most primitive closure demo, so that you can produce a picture of the closure in the brain:

function A() {

function B() {

console. Log("Hello closure!" );

}

return B;

}

var C = A();

c(); Hello closure!

This is the simplest closure in history, it can't be simpler, it's not a closed bag!

With a preliminary understanding, we simply analyze how it differs from the normal function so that we can recognize her from the "boundless crowd".

The above code is translated into natural language as follows:

(1) Defines a common function a

(2) A normal function B is defined in a

(3) return B in a (to be exact, a reference to B is returned in a)

(4) Execute a (), assign the return result of a to the variable C

(5) Execute C ()

Summing up the 5-step operation into a nonsense is:

Function A's intrinsic function B is referenced by a variable C outside of function a

If you make this nonsense, then you'll turn it into a closure definition:

When an intrinsic function is referenced by a variable outside its external function, a closure is formed.

Do not deliberately remember this definition, I tell you the purpose of this definition is to let you understand that the above 5-step operation is to explain the closure of the definition.

So, when you do the above 5 steps, you have defined a closure!

This is the closure package.

2 Effects of closures

Before we get into the role of closures, let's look at the GC mechanism in javascript: in JavaScript, if an object is no longer referenced, the object will be recycled by GC, otherwise the object will remain in memory.

In the above example, B is defined in a, so B relies on a, and the external variable C refers to B, so a is indirectly referenced by C, that is, a is not recycled by GC and is kept in memory. To prove our reasoning, the above example is slightly improved:

function A() {

var count = 0;

function B() {

Count + +;

console. Log(count);

}

return B;

}

var C = A();

c(); 1

c(); 2

c(); 3

Count is a variable in a, its value is changed in B, function B is executed every time, the value of count is accumulated 1 on the original basis. Therefore, the count in a is kept in memory.

That's what closures do, and sometimes we need a module that defines a variable that we want to keep in memory without polluting the global variables, and we can use closures to define the module.

3 High-end notation

The above is actually the simplest and most primitive way of writing, and in practical applications, no one so play, especially in some large JS frame is not so written. The reason why I'm telling you this is that the less distractions, the easier it is to focus on one thing. Here I write a simple demo component using the usual notation:

(function(document) {

var viewport;

var obj = {

init:function(ID) {

viewport = document. Queryselector("#"+ID);

},

addChild:function(child) {

viewport. AppendChild(child);

},

removechild:function(child) {

viewport. RemoveChild(child);

}

}

window. JView = obj;

}) (document);

The function of this component is to initialize a container and then add a child container to the container, or remove a container. The functionality is simple, but here's another concept: executing functions immediately. Just a quick look at the line. The main idea is to understand how the closure function is implemented in this notation.

The above code structure can be divided into two parts: (function () {}) and (), 1th () is an expression, and the expression itself is an anonymous function, so adding () after this expression means executing this anonymous function.

So the execution of this code can be broken down as follows:

var F = function(document) {

var viewport;

var obj = {

init:function(ID) {

viewport = document. Queryselector("#"+ID);

},

addChild:function(child) {

viewport. AppendChild(child);

},

removechild:function(child) {

viewport. RemoveChild(child);

}

}

window. JView = obj;

};

F(document);

In this code, you seem to see the shadow of the closure, but there is no return value in F, it does not seem to have a closure condition, note this code:

Window.jview = obj;

OBJ is an object defined in F, which defines a series of methods that execute Window.jview = obj defines a variable jView in the Window global object and points this variable to the Obj object, where the global variable JView references obj. The function in the Obj object also refers to the variable viewport in F, so the viewport in F is not recycled by GC and is kept in memory, so this writing satisfies the condition of the closure.

4 Simple summing-up language

This is the simplest understanding of closures, of course, the closure has its deeper understanding, this involves more, you need to understand the JS execution Environment (execution context), the active object (Activation object), and scope (scope) and scope chain ( The operating mechanism of scope chain). But as a beginner, do not have to understand these, with a simple understanding, must be used in the actual project, and so you use more, for closures, you will naturally have a deeper understanding!

Let you learn JavaScript closures in minutes

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.