Javascript Closure and example code _JAVASCRIPT skills

Source: Internet
Author: User
Tags addchild closure

Javascript closures

Closures, Javascript is a more important concept, for beginners, closure is a particularly abstract concept, especially the definition of ECMA specification, if there is no combat experience, it is difficult to understand it from the definition. Therefore, this article will not be a description of the concept of closure, directly on dry goods, let you learn to shut down minutes!

1 closures, a quick glimpse

One of the first things I'll do when I'm in touch with a new technology is to find its demo code. For us, looking at code is more comprehensible to the nature of a thing than natural language. In fact, closures are ubiquitous, such as: JQuery, Zepto Core code is included in a large closure, so I first write a simple and original closure, so that you can create in the brain closure of the picture:

function A () {
  function B () {
    console.log ("Hello closure!");
  }
  return B;
}
var C = A ();
C ();//hello closure!

This is the simplest closure.

With a preliminary understanding, we briefly analyze what is different from the normal function, the above code translated into the natural language is as follows:

(1) Define normal function A

(2) Define normal function B in a

(3) return 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 into one sentence is:

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

To process this sentence becomes the definition of closure:

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

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

This is the closure.

2 Use of closures

Before we understand the effect of closures, let's take a look at the GC mechanism in Javascript:

In Javascript, if an object is no longer referenced, the object is reclaimed 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 function a whose value is changed in function B, and every time a function B is executed, the value of Count is incremented by 1 on the original basis. Therefore, the count variable in function A is saved in memory all the time.

When we need to define variables in a module and want them to remain in memory but not "polluting" global variables, we can use closures to define this module.

3 High-end wording

The above is actually the most original writing, and in practical applications, closures and anonymous functions are linked together. Here's how a closure is used:

(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 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. A simple understanding of the line, it is important to understand how this writing is how to achieve closure function.

You can split the above code into two parts: (function () {}) and (), 1th () is an expression, and the expression itself is an anonymous function, so adding () after this expression means executing the 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 function 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 function f, so the viewport in function f is not recycled by GC, and viewport is kept 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!

Thank you for reading, I hope to help you, thank you for your support for this site!

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.