What is a closure:
A closure refers to a function that has access to a variable in the scope of another function.
–《Javascript Advanced Programming》
在这个函数fun2中可以访问另一个函数中的变量a,所以fun2()就是一个闭包。 function fun1 () { var a = 0; function fun2 () { console.log(a); } fun2(); }
1. Call the closure method outside the defined function, escape method:
(1). The function is assigned to a global variable;
var globalVar; function outer() { console.log(‘outer’); function inner(){ console.log(‘inner’); } globalVar = inner; } outer(); // outer globalVar(); // inner;
In this example inner() successfully escapes through the reference of the global variable, and can now be called globally, and can refer to the variable of outer()
(2). 'Rescue' the reference of the inner function by returning the value
function outer() { console.log(‘outer’); function inner(){ console.log(‘inner’); } return inner; } var fn = outer(); // outer fn(); // inner;
In this example inner() escapes successfully by returning the value, and now it can be Called globally, and can refer to variables of outer()
2. The impact of calling closures outside the function: increased memory usage;
Under normal circumstances, the function is after the function call ends The execution environment leaves the environment stack, the defined variables are discarded (disposal is related to the garbage collection mechanism), the active variables (variable objects) will be destroyed, and the memory will be released. But now because the scope chain of the closure includes the variable object of the external function, the variables of the external function may be referenced again. The garbage collection mechanism will not discard the variables of the external function, and the variable objects of the external function are retained in the memory. This increases the memory usage.
3. The relationship between closures and variables: Common misunderstandings and solving techniques in closures
Closures save the entire variable object containing the function, and the external object variables obtained are closure The object variable at the time the package is called is usually the last value of the external function variable.
Example:
function createFun() { var result = []; for ( var i = 0; i < 10; i++) { result[i] = function() { return i; }; } return result; } var result = createFun(); console.log(result5); // 10
The return value of the external function here is an array, and the array values are references to different functions (closures). We will mistakenly think that each closure The return values of the package calls are different, but in fact each function returns the same value. Because when the closure is called, the external function that called the closure has been executed. At this time, i = 10 in the variable object of the external function, and the return value of our closure is i, the closure will obtain the external variable object at the time of the call. , i at this time is 10.
Solution:
function createFun() { var result = []; for ( var i = 0; i < 10; i++) { result[i] = function(num) { return function() { return num; }; }(i); } return result; } var result = createFun(); console.log(result5); // 5
In the loop, we define an anonymous array and assign the result of immediately executing the anonymous function to the array. The anonymous function here is A parameter num, each time i is passed as a parameter to num, each time num is looped, a different value will be obtained, so a different function is returned each time (the difference is that the num value is different), when the array value is called externally, it will be returned Different values, as expected.
4. Pay attention to the this value in the closure
First of all, regarding the this point in the function, we should know that this points to the object that calls the function. If there is no explicit calling object, it points to the window object.
It is easy to mistake the this point in the closure, for example:
var name = “window”; var o = { name: “object”, getName: function() { return function() { return this.name; }; } }; console.log(o.getName()()); // window
It can be seen that the closure this points to the global object. After analysis, you can put o.getName ()() is written as (o.getName())(). This expression is equivalent to executing o.getName() in the first step. This function returns an anonymous function (closure) and then executes it globally. This closure is not called through object o, so this points to the global object.
5. The problem of memory leaks, how to reduce unnecessary memory usage
function assignHandler() { var ele = documnet.getElementById(“somenode”); ele.onclick = function() { console.log(ele.id); }; }
In the above example, the method of defining ele is related to the anonymous function, so ele is saved has a reference to the anonymous function, and the closure will reference the containing function and also reference the ele object, which will cause a circular reference to the object. The ele element (the DOM element takes up a large amount of memory) will always be saved in the memory and cannot be released. The solution The method is as follows:
function assignHandler() { var ele = documnet.getElementById(“somenode”); var id = ele.id; ele.onclick = function() { console.log(id); // 通过id值中介表面上解除了与ele的循环引用 }; ele = null; // 手动解除引用 }
The above is the detailed content of What is closure. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
