Sharing dry goods: let you learn javascript closures in minutes,

Source: Internet
Author: User

Sharing dry goods: let you learn javascript closures in minutes,

Closure is an important concept in javascript. For Beginners, closure is a particularly abstract concept, especially the definition given by the ECMA specification. If there is no practical experience, it is hard for you to understand it by definition. Therefore, this article will not describe the concept of closure in a large space, and let you learn about closure in minutes!

1. Closure-initial experience of love

One of the first things I will do when dealing with a new technology is to find its demo code. For coders, code sometimes understands a thing better than a natural language. Actually, closures are everywhere. For example, the main code of jQuery and zepto is included in a large closure. So I will first write the simplest and most primitive closure demo, so that you can create a closure image in your 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 cannot be simpler, but it is not a closure!

With a preliminary understanding, we can simply analyze what is different from a common function, so that we can recognize "she" from the eyes of "the vast sea of people ".

The above code is translated into a natural language as follows:

  • (1) defines A common function.
  • (2) define common function B in
  • (3) return B in A (specifically, return B's reference in)
  • (4) execute A () and assign the returned result of A to variable c
  • (5) execute c ()

To sum up these five steps, we can say that:

Function A's internal function B is referenced by A variable c outside function.

After processing this nonsense sentence, it becomes the definition of closure:

When an internal function is referenced by a variable other than its external function, a closure is formed.

Do not deliberately remember this definition. I tell you that the purpose of this definition is to let you understand that the above five steps are to elaborate the definition of the closure.

Therefore, when you perform the preceding five steps, you have defined a closure!

This is the closure.

2. Functions of closures

Before learning about the function of the closure, let's take a look at the GC mechanism in javascript: In javascript, if an object is no longer referenced, it will be recycled by GC, otherwise, the object will be stored in the memory.

In the above example, B is defined in A, so B Depends On A, and the external variable c references B, so A is indirectly referenced by c, that is, A will not be recycled by GC and will be stored in the memory all the time. 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();// 1c();// 2c();// 3

Count is A variable in A, and its value is changed in B. Every execution of function B, the value of count is accumulated by 1 on the basis of the original. Therefore, the count in A is always stored in the memory.

This is the function of the closure. Sometimes we need to define a variable in a module: we want this variable to be kept in the memory but it will not "pollute" the global variable. At this time, we can use closures to define this module.

3. High-end writing

The above writing method is actually the simplest and most primitive writing method, but in actual application, no one is playing this way, especially in some large JS frameworks. The reason why I want to tell you this is that the less interference, the easier it is to focus on one thing. Below I will write a simple demo component using a common method:

(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);


This component is used to initialize a container, and then add sub-containers to the container or remove a container. The function is simple, but this involves another concept: immediate execution of the function. Just take a look. We need to understand how this writing method implements the closure function.

The above code structure can be divided into two parts: (function () {}) () the red part is an expression, and the expression itself is an anonymous function, therefore, adding () after this expression indicates that the anonymous function is executed.

Therefore, the code execution process 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, we can see the shadow of the closure, but f does not return any values, and it does not seem to have the closure condition. Pay attention to this Code:

Window. jView = obj;
Obj is an object defined in f. This object defines a series of methods to execute window. jView = obj defines a variable jView in the window Global Object and points the variable to the obj object. That is, the global variable jView references obj. the function in the obj object references the variable viewport in f, so the viewport in f will not be recycled by GC and will be stored in the memory all the time. Therefore, this method meets the condition of closure.

4. Simple Summary

This is the simplest understanding of the closure. Of course, the closure has a deeper understanding. This involves more. You need to understand the execution context of JS) action object, scope, and scope chain. But as a beginner, you do not need to understand this for the time being. With a simple understanding, you must use it in the actual project. When you use more, for closures, you will naturally have a deeper understanding!

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Javascript: a deep understanding of js closures
  • Javascript closures and applications that must be known in front-end development
  • JavaScript anonymous functions and closures)
  • JavaScript closures do not understand. I understand JavaScript closures.
  • The js bind function uses the closure to save the execution context.
  • Scope chains and closures in JavaScript

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.