A simple understanding of JavaScript's closure concept __java

Source: Internet
Author: User
Tags addchild closure

Original source: https://my.oschina.net/ym1983/blog/829314

Closures are an important concept in JavaScript, and for beginners, closures are a particularly abstract concept, especially the definition given by the ECMA specification, and it is difficult to understand it by definition without actual combat experience. Therefore, this article will not be a large description of the concept of closure, directly on dry goods, so that you learn to shut down minutes.

1 closures – The first experience of love

One of the first things I would do when I'm in touch with a new technology is: Find the demo code. For code farmers, code can sometimes understand a thing better than natural language. In fact, closures are everywhere, such as: JQuery, Zepto's main code is included in a large closure, so I first write a simple and original closure demo, so that you can create a closure in the brain screen:

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 not be simple, and then simple is not a closure.

With a preliminary understanding, we briefly analyze how it differs from ordinary functions, so that we can recognize her from the "boundless crowd".

The code above is translated into natural language as follows:

(1) defines a normal function a

(2) A normal function B is defined in a

(3) return B in a (exactly, return a reference to B in a)

(4) execute a () and assign the return result of a to the variable C

(5) Implementation of C ()

The 5-step operation summed up in a sentence of nonsense is:

The internal function B of function A is referenced by a variable C outside function a

To process this nonsense is to become the definition of closure:

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

Don't try to remember this definition, I'm telling you the purpose of this definition is to make you understand that the 5-step procedure above is to illustrate the definition of closure.

Therefore, when you perform the 5 steps above, you have defined a closure.

This is the closure.

2 Function of closure

Before we understand the effect of closures, let's look at the GC mechanism in javascript: in JavaScript, if an object is no longer referenced, the object is collected by GC, otherwise the object is kept in memory.

In the example above, B is defined in a, so B depends on a, and the external variable C refers to B, so a is indirectly referenced by C, that is, a is not reclaimed by GC and is kept in memory. To prove our reasoning, the example above 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, and its value is changed in B, and every time a function B is executed, the value of Count is incremented by 1 on the original basis. Therefore, the count in a is kept in memory.

This is what closures do, and sometimes we need to define a variable in a module: we want this variable to be stored in memory but not "polluting" the global variable, at which point we can use the closure to define the module.

3 High-end wording

The above is actually the simplest and the most original writing, and in the actual application, no one plays this way, especially in some large JS framework is not so written. The reason why I have to tell you this is that the less disturbing you are, the easier it is to focus on one thing. Here's how 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;

},

removechild:function (child) {

viewport.removechild;

}

window.jview = obj;

}) (document);

The function of this component is to initialize a container, and then you can add a child container to the container, or you can remove a container. The function is simple, but here's another concept: Execute the function immediately. Just a quick look at the line. The main is to understand how this writing is to achieve the closure function.

The above code structure can be divided into two parts: (function () {}) and (), the 1th () is an expression, and the expression itself is an anonymous function, so add () after this expression to represent the execution of 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 seems to see the shadow of the closure, but there is no return value in F, does not seem to have the closure of the conditions, note this code:

Window.jview = obj;

OBJ is an object defined in F that defines a series of methods that executes Window.jview = obj defines a variable jView in the Window global object and points the variable to the Obj object, which is the global variable JView references obj. The functions in the Obj object refer to the variable viewport in F, so the viewport in F is not collected by GC and will be saved in memory, so this method satisfies the closure condition.

4 Simple concluding words

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

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.