Easy-to-understand JavaScript closure example code
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.
