Javascript closure details and example code, and javascript details

Source: Internet
Author: User

Javascript closure details and example code, and javascript details

Javascript Closure

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 difficult 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.

One of the first things I will do when dealing with a new technology is to find its demo code. For us, looking at code can better understand the essence of a thing than natural language. Actually, closures are everywhere. For example, the core code of jQuery and zepto is included in a large closure. So let's first write the simplest and most primitive closure, 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.

With a preliminary understanding, let's briefly analyze what is different from a common function. The above code is translated into a natural language as follows:

(1) define common function

(2) define common function B in

(3) return B in

(4) execute A and assign the returned result of A to variable C

(5) execute C

Summarize the five steps into one sentence:

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

After processing this 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.

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

This is the closure.

2. Use 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, the object 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 to say, 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 function A. Its value is changed in function B. Every time function B executes the variable, the count value increases by 1 based on the original one. Therefore, the count variable in function A is always stored in the memory.

When we need to define some variables in the module and want these variables to be kept in the memory but will not "pollute" the global variables, we can use closures to define this module.

 3 high-end writing

The preceding method is actually the most primitive method. In actual applications, the closure and anonymous function are associated for use. Below is a common method of writing a closure:

(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. Let's just take a look. What we need to understand is how this writing method implements the closure function.

The code above can be split into two parts: (function () {}) and (). 1st () is an expression, and this 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 function f. This object defines a series of methods and runs 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 function f, so the viewport in function f will not be recycled by GC, And the viewport will be stored in the memory all the time, therefore, this write method satisfies the closure conditions.

 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) activity object 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!

Thank you for reading this article. I hope it will 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.