1. "Closure is accessing variables across scopes."
[Example 1]
var name = 'wangxi' function user () { // var name = 'wangxi' function getName () { console.log(name) } getName() } user() // wangxi
To get the name in the getName function, first search for name in the scope of the getName function, but it is not found, and then search in the scope of the user function, but it is also not found. Continue to trace back upward and find that name exists in the global scope, so Get the name value and print it. It is easy to understand here, that is, the variables all exist in the specified scope. If the desired variable cannot be found in the current scope, the search will continue in the parent scope through the scope chain until the first one with the same name is found. variable (or if it cannot be found, a ReferenceError will be thrown). This is the concept of scope chain in js, that is, the child scope can access the variables in the parent scope according to the scope chain. What if, on the contrary, the parent scope wants to access the variables in the child scope? ——This needs to be achieved through closure.
[Example 2]
function user () { var name = 'wangxi' return function getName () { return name } } var userName = user()() console.log(userName) // wangxi
Analyzing the code, we know that name is a local variable that exists within the scope of the user function. Under normal circumstances, it acts externally The name variable cannot be accessed in the domain (here is the global), but through closure (returning a function containing the variable, here is the getName function), the variable can be accessed across scopes (external access to internal). Therefore, the above statement should be completely understood as:
Closure is to access variables across scopes - the inner scope can maintain a reference to the variables in the outer scope so that (more) the outer scope can Access variables in the inner scope. (If you still don’t understand, read the next analysis)
2. "Closure: Dad is executed in the environment of grandpa, and the grandson is returned in dad. Originally, After the father is executed, the father's environment should be cleared, but the grandson references the father's environment, so the father cannot release it. Simply put, a closure is an object that references the parent environment, and from there. An object returned from the parent environment to a higher-level environment. "
How do you understand this? First look at the code below:
[Example 3]
function user () { var name = 'wangxi' return name } var userName = user() console.log(userName) // wangxi
Q: Is this a closure?
Answer: Of course not. First, you need to understand what a closure is. Although it seems that the local variable name in the user function is accessed in the global scope, the problem is that after user is executed, name is also destroyed, that is, the life cycle of the local variable in the function only exists in During the function's declaration cycle, the function is destroyed and the variables within the function are automatically destroyed.
But using closures is the opposite. After the function is executed, the life cycle ends, but the variables in the outer scope referenced by the closure still exist, and will always exist until the scope that executes the closure is Destroy, the local variables here will be destroyed (if the closure is referenced in the global environment, the scope referenced by the closure will only be destroyed when the global environment is destroyed, such as the program ends, the browser is closed, etc.). Therefore, in order to avoid memory loss caused by closures, it is recommended to manually destroy closures after use. Still the same as Example 2 above, slightly modified:
[Example 4]
function user () { var name = 'wangxi' return function getName () { return name } } var userName = user()() // userName 变量中始终保持着对 name 的引用 console.log(userName) // wangxi userName = null // 销毁闭包,释放内存
[Why user()() has two brackets: Execute user() returns the getName function. To obtain the name variable, you need to execute the returned getName function once, so it is user()()】
According to point 2, analyze the code: in the global scope Created the userName variable (grandfather), saved the reference to the final return result of the user function (that is, the value of the local variable name), executed user()() (father), and returned name (grandson). Under normal circumstances, in After executing user()(), user's environment (father) should be cleared, but because the returned result name (grandson) refers to father's environment (because name originally exists in the scope of user), user The environment cannot be released (resulting in memory loss).
So ["A closure is an object that references the parent environment and returns an object from the parent environment to a higher-level environment."] How to understand?
Let’s put it another way: if a function refers to an object in the parent environment and returns the object to the higher-level environment in this function, then this function is a closure.
Look at the above example:
The getName function refers to the object (variable name) in the user (parent) environment, and returns the name variable to the global environment (higher level) in the function environment), therefore, getName is a closure.
3. "Functions in JavaScript run in the scope in which they are defined, not the scope in which they are executed."
This sentence is very helpful for understanding the reference to variables in closures. Let’s look at the following example:
var name = 'Schopenhauer' function getName () { console.log(name) } function myName () { var name = 'wangxi' getName() } myName() // Schopenhauer
If the output result of executing myName() is different from what you imagined, you have to go back and look at the sentence above Yes,
JavaScript 中的函数运行在它们被定义的作用域里,而不是它们被执行的作用域里
执行 myName,函数内部执行了 getName,而 getName 是在全局环境下定义的,因此尽管在 myName 中定义了变量 name,对getName 的执行并无影响,getName 中打印的依然是全局作用域下的 name。
我们稍微改一下代码:
var name = 'Schopenhauer' function getName () { var name = 'Aristotle' var intro = function() { // 这是一个闭包 console.log('I am ' + name) } return intro } function showMyName () { var name = 'wangxi' var myName = getName() myName() } showMyName() // I am Aristotle
结果和你想象的一样吗?结果留作聪明的你自己分析~
以上就是对 js 中闭包的理解,如果有误,欢迎指正。最后引用一段知乎问题下关于闭包概念的一个回答。
什么是闭包?
简单来说,闭包是指可以访问另一个函数作用域变量的函数,一般是定义在外层函数中的内层函数。
为什么需要闭包?
局部变量无法共享和长久的保存,而全局变量可能造成变量污染,所以我们希望有一种机制既可以长久的保存变量又不会造成全局污染。
特点
占用更多内存
不容易被释放
何时使用?
变量既想反复使用,又想避免全局污染
如何使用?
定义外层函数,封装被保护的局部变量。
定义内层函数,执行对外部函数变量的操作。
外层函数返回内层函数的对象,并且外层函数被调用,结果保存在一个全局的变量中。
The above is the detailed content of A simple explanation of closures in JS. For more information, please follow other related articles on the PHP Chinese website!

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.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools
