What is a closure in javascript? How to use javascript closure?
The so-called "closure" refers to an expression (usually a function) that has many variables and an environment bound to these variables, so these variables are also part of the expression.
Regarding closures, the simplest description is that ECMAScript allows the use of internal functions - that is, the function definition and function expression are located in the function body of another function. Furthermore, these inner functions have access to all local variables, parameters, and other inner functions declared in the outer function in which they exist. A closure is formed when one of these inner functions is called outside the outer function that contains them. That is, the inner function will be executed after the outer function returns. When this inner function is executed, it still must access the local variables, parameters and other inner functions of its outer function. The values of these local variables, parameters, and function declarations (initially) are the values when the outer function returns, but are also affected by the inner function.
In short, the function of the closure is that after the out function is executed and returns, the closure prevents Javascript's garbage collection mechanism GC from reclaiming the resources occupied by the out function, because the inner function of the out function has Execution depends on the variables in the out function.
Two characteristics of closure:
1. As a reference to a function variable - it is activated when the function returns.
2. A closure is a stack area that does not release resources when a function returns.
Example 1:
<script type="text/javascript"> function setupSomeGlobals() { // Local variable that ends up within closure var num = 666; // Store some references to functions as global variables gAlertNumber = function() { alert(num); } gIncreaseNumber = function() { num++; } gSetNumber = function(x) { num = x; } } </script> <button onclick="setupSomeGlobals()">生成 - setupSomeGlobals()</button> <button onclick="gAlertNumber()">输出值 - gAlertNumber()</button> <button onclick="gIncreaseNumber()">增加 - gIncreaseNumber()</button> <button onclick="gSetNumber(5)">赋值5 - gSetNumber(5)</button>
Example 2:
<script type="text/javascript"> function newClosure(someNum, someRef) { // Local variables that end up within closure var num = someNum; var anArray = [1,2,3]; var ref = someRef; return function(x) { num += x; anArray.push(num); alert('num: ' + num + ' nanArray ' + anArray.toString() + ' nref.someVar ' + ref.someVar); } } var closure1 = newClosure(40, {someVar:' never-online'}) var closure2 = newClosure(99, {someVar:' BlueDestiny'}) closure1(4) closure2(3) </script>
Example 3:
<script language="javascript"> /* 声明一个全局变量 - getImgInPositionedDivHtml - 并将一次调用一个外部函数表达式返回的内部函数赋给它。 这个内部函数会返回一个用于表示绝对定位的 DIV 元素包围着一个 IMG 元素 的 HTML 字符串,这样一来, 所有可变的属性值都由调用该函数时的参数提供: */ var getImgInPositionedDivHtml = (function(){ /* 外部函数表达式的局部变量 - buffAr - 保存着缓冲数组。这个数组只会被创建一次,生成的数组实例对内部函数而言永远是可用的 因此,可供每次调用这个内部函数时使用。 其中的空字符串用作数据占位符,相应的数据 将由内部函数插入到这个数组中: */ var buffAr = [ '<div id="', '', //index 1, DIV ID 属性 '" style="position:absolute;top:', '', //index 3, DIV 顶部位置 'px;left:', '', //index 5, DIV 左端位置 'px;width:', '', //index 7, DIV 宽度 'px;height:', '', //index 9, DIV 高度 'px;overflow:hidden;\"><img src=\"', '', //index 11, IMG URL '\" width=\"', '', //index 13, IMG 宽度 '\" height=\"', '', //index 15, IMG 调蓄 '\" alt=\"', '', //index 17, IMG alt 文本内容 '\"><\/div>' ]; /* 返回作为对函数表达式求值后结果的内部函数对象。 这个内部函数就是每次调用执行的函数 - getImgInPositionedDivHtml( ... ) - */ return (function(url, id, width, height, top, left, altText){ /* 将不同的参数插入到缓冲数组相应的位置: */ buffAr[1] = id; buffAr[3] = top; buffAr[5] = left; buffAr[13] = (buffAr[7] = width); buffAr[15] = (buffAr[9] = height); buffAr[11] = url; buffAr[17] = altText; /* 返回通过使用空字符串(相当于将数组元素连接起来) 连接数组每个元素后形成的字符串: */ return buffAr.join(''); }); //:内部函数表达式结束。 })();//自调用 alert(getImgInPositionedDivHtml);//显示返回的函数 alert(getImgInPositionedDivHtml("img.gif","img",100,50,0,0,"Test")); </script>
Explanation: The key trick is to execute an in-line function expression creates an additional execution environment, and the inner function returned by the function expression is used as a function in external code. At this time, the buffer array is defined as a local variable of the function expression. The function expression only needs to be executed once, and the array is created once and can be reused by functions that depend on it.
The above is the detailed content of What is a closure in javascript? How to use javascript closure?. 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

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

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











ccsvchst.exe is a common process file that is part of the Symantec Endpoint Protection (SEP) software, and SEP is an endpoint protection solution developed by the well-known network security company Symantec. As part of the software, ccsvchst.exe is responsible for managing and monitoring SEP-related processes. First, let’s take a look at SymantecEndpointProtection(

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Dual-core browser is a browser software that integrates two different browser cores. The kernel is the core part of the browser, responsible for rendering web content and executing web scripts and other functions. Traditional browsers generally use only a single kernel, such as IE browser using Trident kernel, Chrome browser using WebKit/Blink kernel, Firefox browser using Gecko kernel, etc. The dual-core browser integrates two different cores into one browser, and users can freely switch between them as needed. The emergence of dual-core browsers

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
