Home > Web Front-end > JS Tutorial > body text

What is a closure in javascript? How to use javascript closure?

伊谢尔伦
Release: 2017-07-20 15:10:32
Original
1694 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template