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

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools