search
HomeWeb Front-endJS TutorialWhat 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(&#39;num: &#39; + num + 
&#39; nanArray &#39; + anArray.toString() + 
&#39; nref.someVar &#39; + ref.someVar); 
} 
} 
var closure1 = newClosure(40, {someVar:&#39; never-online&#39;}) 
var closure2 = newClosure(99, {someVar:&#39; BlueDestiny&#39;}) 
closure1(4) 
closure2(3) 
</script>

Example 3:

<script language="javascript"> 
/* 声明一个全局变量 - getImgInPositionedDivHtml - 并将一次调用一个外部函数表达式返回的内部函数赋给它。 
这个内部函数会返回一个用于表示绝对定位的 DIV 元素包围着一个 IMG 元素 的 HTML 字符串,这样一来, 
所有可变的属性值都由调用该函数时的参数提供: 
*/ 
var getImgInPositionedDivHtml = (function(){ 
/* 外部函数表达式的局部变量 - buffAr - 保存着缓冲数组。这个数组只会被创建一次,生成的数组实例对内部函数而言永远是可用的 
因此,可供每次调用这个内部函数时使用。 
其中的空字符串用作数据占位符,相应的数据 
将由内部函数插入到这个数组中: 
*/ 
var buffAr = [ 
&#39;<div id="&#39;, 
&#39;&#39;, //index 1, DIV ID 属性 
&#39;" style="position:absolute;top:&#39;, 
&#39;&#39;, //index 3, DIV 顶部位置 
&#39;px;left:&#39;, 
&#39;&#39;, //index 5, DIV 左端位置 
&#39;px;width:&#39;, 
&#39;&#39;, //index 7, DIV 宽度 
&#39;px;height:&#39;, 
&#39;&#39;, //index 9, DIV 高度 
&#39;px;overflow:hidden;\"><img src=\"&#39;, 
&#39;&#39;, //index 11, IMG URL 
&#39;\" width=\"&#39;, 
&#39;&#39;, //index 13, IMG 宽度 
&#39;\" height=\"&#39;, 
&#39;&#39;, //index 15, IMG 调蓄 
&#39;\" alt=\"&#39;, 
&#39;&#39;, //index 17, IMG alt 文本内容 
&#39;\"><\/div>&#39; 
]; 
/* 返回作为对函数表达式求值后结果的内部函数对象。 
这个内部函数就是每次调用执行的函数 
- 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(&#39;&#39;); 
}); //:内部函数表达式结束。 
})();//自调用 
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!

Statement
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

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.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

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 Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

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

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

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.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function