Home > Web Front-end > JS Tutorial > body text

Easy-to-understand JavaScript closure example code

黄舟
Release: 2017-03-10 15:16:22
Original
990 people have browsed it

Closure is a unique concept in JavaScript. For beginners, closure is a particularly abstract concept, especially the definition given by the ECMA specification. Without practical experience, it is difficult to understand it from the definition. Therefore, this article will not describe the concept of closure in a long way, but will go directly to the practical information so that you can learn closure in minutes!

1 Closure – The first experience of love

When I come into contact with a new technology, the first thing I do is: look for it demo code. For coders, code can sometimes understand a thing better than natural language. In fact, closures are everywhere. For example, the main codes of jQuery and zepto are all included in a large closure. So below I will write the simplest and most primitive closure demo to help you create closures in your brain. Picture:

function A(){
    function B(){
       console.log("Hello Closure!");
    }
    return B;
}
var c = A();
c();//Hello Closure!
Copy after login

This is the simplest closure in history. It cannot be simpler. No matter how simple it is, it is no longer a closure!

After having a preliminary understanding, let's briefly analyze how it is different from ordinary functions, so that we can recognize "her" at a glance among the "huge crowd".

The above code is translated into natural language as follows:

(1) Defines an ordinary function A

(2) Defines an ordinary function B

in A (3) Return B in A (to be precise, return a reference to B in A)

(4) Execute A() and assign the return result of A to the variable c

( 5) Execute c()

Summarize these 5 steps into a nonsense sentence:

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

Reprocess this nonsense and it becomes the definition of closure:

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

Don’t deliberately remember this definition. The purpose of telling you this definition is to let you understand that the above 5 steps are to elaborate on the definition of closure.

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

This is closure.

2 The role of closure

Before understanding the role of closure, let’s first understand the GC mechanism in javascript: In javascript, if an object is no longer referenced, then this object It will be recycled by GC, otherwise this object will always be stored in memory.

In the above example, 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 will not be recycled by GC. , will always be saved 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
Copy after login

count is a variable in A, and its value is changed in B. The function Every time B is executed, the value of count will increase by 1 based on the original value. Therefore, the count in A is always kept in memory.

This is the role of closure. Sometimes we need to define such a variable in a module: we hope that this variable will always be saved in memory but will not "pollute" the global variable. At this time, we can Use closures to define this module.

3 High-end writing method

The above writing method is actually the simplest and most primitive writing method, but in actual applications, no one does it this way, especially in some large JS frameworks. Write. The reason why I tell you this way of writing is because the fewer distractions, the easier it is to focus on one thing. Below I use the commonly used writing method to write a simple demo component:

(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);
Copy after login

The function of this component is to initialize a container and then add children to the container. Container, you can also remove a container. The function is very simple, but another concept is involved here: executing the function immediately. Just understand it briefly. The main thing is 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 this expression itself is an anonymous function, so add ( after this expression ) means executing this anonymous function.

So the execution process of this code can be decomposed 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);
Copy after login

It seems that the shadow of closure is seen in this code, but There is no return value in f, and it seems that it does not meet the conditions for closure. Pay attention to this code:

window.jView = obj;
Copy after login

obj is an object defined in f. This A series of methods are defined in the object. Executing window.jView = obj means defining a variable jView in the window global object and pointing this variable to the obj object. That is, the global variable jView refers to obj. And the functions in the obj object refer to The variable viewport in f, so the viewport in f will not be recycled by GC and will always be saved in memory, so this writing method meets the conditions of closure.

4 Simple summary

This is the simplest understanding of closures. Of course, closures have a deeper understanding. This is more involved. You need to understand the execution environment of JS ( execution context), active objects (call objects), and the operating mechanisms of scopes and scope chains. But as a beginner, you don’t need to understand these for now. After you have a simple understanding, you must use it in actual projects. When you use it more, you will naturally have a deeper understanding of closures!

The above is the detailed content of Easy-to-understand JavaScript closure example code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!