Home Web Front-end JS Tutorial Characteristic analysis of JS closure

Characteristic analysis of JS closure

Mar 06, 2018 pm 01:55 PM
javascript analyze characteristic

In the body tag, add a u tag with the id node, and there are 5 li tags under the ul tag. How to pop up the li subscript when clicking on different li tags?
1) First you need to get the ul node var node = document.getElementsById('node')
2) Get the child node under the node node var list = node.children
**3) Add onclick to the child node loop Event (note here that there will be closure problems). for(var i=0;i< list.length; i++){
list[i].onclick = function()console.log(i)}}, from the printed results, it is found that each time the output is 7. **
4) Analysis output 7, because i is declared as a global variable using var, pointing to the same address. After the loop is executed, the value of i is 7, so the result printed in each loop is 7
Use two ways to solve it, 1) declare block-level scope variables, and use let j = i every time i is passed in , take over.

let j = i; 
list[i].onclick = function(){console.log(j)}
Copy after login

In the function method, the block-level variable j is called, and this variable will not be garbage collected. Each for loop points to a different address, so when the click event is triggered, its subscript can be printed correctly. 2) Use closures to solve the problem.

list[i].onclick = function(i){ 
return function(){console.log(i)}。 
}
Copy after login

**Interpretation of closures
A closure is a function that can read the internal variables of other functions. In the JavaScript language, only subfunctions inside a function can read local variables. Closures can be simply understood as "functions defined inside a function". In essence, a closure is a bridge connecting the inside of a function to the outside of the function.

Note: Using closures will cause the variables in the function to be stored in memory, which consumes a lot of memory. Therefore, closures cannot be abused, which will cause performance problems on the web page and may cause memory problems in IE browsers. leakage. . The final solution is to delete all unused local variables before exiting the function.

Use other people’s examples. For your reference

var name = "this window";
var object = {
    name :"my object",
    getNameFunc:function () {
        return function () {
            return this.name;
        }
    }
}
alert(object.getNameFunc()());/弹出this window2 。此时this对象指向window对象
var object2 = {
    name: "my object",
    getNameFunc2: function () {
        var that = th is;
        return function () {
            return that.name;
        }
    }
}
alert(‘that’+object2.getNameFunc2()()); ///弹出my object。此时this对象指向object2对象
Copy after login

Related recommendations:

Simple understanding of JS closures

Detailed explanation of common forms of JS closures

Sample code sharing for JS closure usage

The above is the detailed content of Characteristic analysis of JS closure. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

Choose the applicable Go version, based on needs and features Choose the applicable Go version, based on needs and features Jan 20, 2024 am 09:28 AM

With the rapid development of the Internet, programming languages ​​are constantly evolving and updating. Among them, Go language, as an open source programming language, has attracted much attention in recent years. The Go language is designed to be simple, efficient, safe, and easy to develop and deploy. It has the characteristics of high concurrency, fast compilation and memory safety, making it widely used in fields such as web development, cloud computing and big data. However, there are currently different versions of the Go language available. When choosing a suitable Go language version, we need to consider both requirements and features. head

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Analyze the advantages and disadvantages of static positioning technology Analyze the advantages and disadvantages of static positioning technology Jan 18, 2024 am 11:16 AM

Analysis of the advantages and limitations of static positioning technology With the development of modern technology, positioning technology has become an indispensable part of our lives. As one of them, static positioning technology has its unique advantages and limitations. This article will conduct an in-depth analysis of static positioning technology to better understand its current application status and future development trends. First, let’s take a look at the advantages of static positioning technology. Static positioning technology achieves the determination of position information by observing, measuring and calculating the object to be positioned. Compared with other positioning technologies,

Analyze and solve the reasons why Tomcat crashes Analyze and solve the reasons why Tomcat crashes Jan 13, 2024 am 10:36 AM

Tomcat crash cause analysis and solutions Introduction: With the rapid development of the Internet, more and more applications are developed and deployed on servers to provide services. As a common JavaWeb server, Tomcat has been widely used in application development. However, sometimes we may encounter problems with Tomcat crashing, which will cause the application to not run properly. This article will introduce the analysis of the causes of Tomcat crash, provide solutions, and give specific code examples.

C++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of ​​a circle of a given radius and returns it as output.

Master the key features and application scenarios of Golang middleware Master the key features and application scenarios of Golang middleware Mar 20, 2024 pm 06:33 PM

As a fast and efficient programming language, Golang is also widely used in the field of web development. Among them, middleware, as an important design pattern, can help developers better organize and manage code, and improve the reusability and maintainability of code. This article will introduce the key features and application scenarios of middleware in Golang, and illustrate its usage through specific code examples. 1. The concept and function of middleware. As a plug-in component, middleware is located in the request-response processing chain of the application. It is used

See all articles