1. The scope of variables
To understand closures, you must first understand the special variable scope of Javascript.
The scope of variables is nothing more than two types: global variables and local variables.
The special thing about Javascript language is that global variables can be read directly inside the function.
var n=999;
function f1() {
alert(n);
}
f1(); // 999
On the other hand, local variables within the function cannot be read outside the function.
Function f1(){
var n=999 ;
}
alert(n); // error
There is something to note here. When declaring variables inside a function, you must use the var command. If you don't use it, you are actually declaring a global variable!
Function f1(){
n=999;
}
f1();
alert(n); // 999
2. How to read local variables from the outside?
For various reasons, we sometimes need to get local variables within a function. However, as mentioned before, this is not possible under normal circumstances and can only be achieved through workarounds.
That is to define another function inside the function.
Function f1(){
n=999;
function f2(){
alert(n); // 999
}
}
In the above code, function f2 is included in function f1 Internally, at this time, all local variables inside f1 are visible to f2. But the reverse doesn't work. The local variables inside f2 are invisible to f1. This is the unique "chain scope" structure of the Javascript language.
The child object will search for the variables of all parent objects level by level. Therefore, all variables of the parent object are visible to the child object, but not vice versa.
Since f2 can read local variables in f1, then as long as f2 is used as the return value, can’t we read its internal variables outside f1?
Function f1(){
n=999;
Function f2(){
alert(n);
}
return f2;
}
var result=f1();
result(); // 999
3. The concept of closure
The f2 function in the code in the previous section is a closure.
The definition of "closure" in various professional literature is very abstract and difficult to understand. My understanding is that a closure is a function that can read the internal variables of other functions.
Since in the Javascript language, only sub-functions inside the function can read local variables, closures can be simply understood as "functions defined inside a function".
So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.
4. Uses of closures
Closures can be used in many places. Its greatest uses are two. One is to read the variables inside the function as mentioned earlier, and the other is to keep the values of these variables in memory.
How to understand this sentence? Please look at the code below.
Function f1(){
var n=999 ;
nAdd=function(){n =1}
function f2(){
alert(n);
}
return f2;
}
var result= f1();
result(); // 999
nAdd();
result(); // 1000
In this code, result is actually the closure f2 function. It was run twice, the first time the value was 999, the second time the value was 1000. This proves that the local variable n in function f1 is always stored in memory and is not automatically cleared after f1 is called.
Why is this happening? The reason is that f1 is the parent function of f2, and f2 is assigned to a global variable, which causes f2 to always be in memory, and the existence of f2 depends on f1, so f1 is always in memory and will not be deleted after the call is completed. , recycled by the garbage collection mechanism (garbage collection).
Another thing worth noting in this code is the line "nAdd=function(){n =1}". First of all, the var keyword is not used before nAdd, so nAdd is a global variable, not a local variable. variable. Secondly, the value of nAdd is an anonymous function, and this
anonymous function itself is also a closure, so nAdd is equivalent to a setter, which can operate on local variables inside the function outside the function.
5. Points of note when using closures
1) Since closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page. , which may cause memory leaks in IE. The solution is to delete all unused local variables before exiting the function.
2) The closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to
change the value of the variable inside the parent function.
6. Questions to think about
If you can understand the results of the following code, you should understand the operating mechanism of closures.
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
JavaScript closure example
function outerFun()
{
var a=0;
function innerFun()
{
a ;
alert(a);
}
}
innerFun()
The above code is wrong. The scope of innerFun() is in outerFun( ), it is wrong to call it outside outerFun().
is changed to the following, which is a closure:
function outerFun() {
var a=0;
function innerFun() {
a;
alert(a);
}
return innerFun; //Note here
}
var obj=outerFun();
obj(); //The result is 1
obj(); //The result is 2
var obj2=outerFun();
obj2(); //The result is 1
obj2(); //The result is 2
What is a closure:
When an inner function is referenced outside the scope in which it is defined, a closure of the inner function is created. If the inner function references variables located in the outer function, these variables will not be in memory after the outer function is called. are released because the closure requires them.
Look at another example
function outerFun() {
var a =0;
alert(a);
}
var a=4;
outerFun();
alert(a );
The result is 0,4. Because the var keyword is used inside the function to maintain the scope of a inside outFun().
Look at the following code again:
function outerFun()
{
//No var
a =0;
alert(a);
}
var a=4;
outerFun();
alert(a);
The result is 0,0 which is really strange, why?
Scope chain is a term that describes a path along which the value of a variable can be determined. When a=0 is executed, because the var key is not used word, so the assignment operation will follow the scope chain to var a=4; and change its value.
If you don’t understand JavaScript closures very well, then please read the article reprinted below: (Reprinted: http:/ /www.felixwoo.com/archives/247)
1. What is closure? The official explanation is: a closure is 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.
I believe that few people can understand this sentence directly, because his description is too academic. In fact, this sentence is: all functions in JavaScript are closures. But generally speaking, nested functions are. The resulting closure is more powerful and is what we call "closure" most of the time. Look at the following code:
function a() {
var i = 0;
function b() { alert( i); }
return b;
}
var c = a();
c();
这段代码有两个特点:
1、函数b嵌套在函数a内部;
2、函数a返回函数b。
引用关系如图:
这样在执行完var c=a()后,变量c实际上是指向了函数b,再执行c()后就会弹出一个窗口显示i的值(第一次为1)。这段代码其实就创建了一个闭包,为什么?因为函数a外的变量c引用了函数a内的函数b,就是说:
当函数a的内部函数b被函数a外的一个变量引用的时候,就创建了一个闭包。
让我们说的更透彻一些。所谓“闭包”,就是在构造函数体内定义另外的函数作为目标对象的方法函数,而这个对象的方法函数反过来引用外层函数体中的临 时变量。这使得只要目标 对象在生存期内始终能保持其方法,就能间接保持原构造函数体当时用到的临时变量值。尽管最开始的构造函数调用已经结束,临时变量的名称也都消失了,但在目 标对象的方法内却始终能引用到该变量的值,而且该值只能通这种方法来访问。即使再次调用相同的构造函数,但只会生成新对象和方法,新的临时变量只是对应新 的值,和上次那次调用的是各自独立的。
二、闭包有什么作用?
简而言之,闭包的作用就是在a执行完并返回后,闭包使得Javascript的垃圾回收机制GC不会收回a所占用的资源,因为a的内部函数b的执行需要依赖a中的变量。这是对闭包作用的非常直白的描述,不专业也不严谨,但大概意思就是这样,理解闭包需要循序渐进的过程。
在上面的例子中,由于闭包的存在使得函数a返回后,a中的i始终存在,这样每次执行c(),i都是自加1后alert出i的值。
那 么我们来想象另一种情况,如果a返回的不是函数b,情况就完全不同了。因为a执行完后,b没有被返回给a的外界,只是被a所引用,而此时a也只会被b引 用,因此函数a和b互相引用但又不被外界打扰(被外界引用),函数a和b就会被GC回收。(关于Javascript的垃圾回收机制将在后面详细介绍)
三、闭包内的微观世界 如果要更加深入的了解闭包以及函数a和嵌套函数b的关系,我们需要引入另外几个概念:函数的执行环境(excution context)、活动对象(call object)、作用域(scope)、作用域链(scope chain)。以函数a从定义到执行的过程为例阐述这几个概念。
当定义函数a的时候,js解释器会将函数a的作用域链(scope chain)设置为定义a时a所在的“环境”,如果a是一个全局函数,则scope chain中只有window对象。
当执行函数a的时候,a会进入相应的执行环境(excution context)。
在创建执行环境的过程中,首先会为a添加一个scope属性,即a的作用域,其值就为第1步中的scope chain。即a.scope=a的作用域链。
然后执行环境会创建一个活动对象(call object)。活动对象也是一个拥有属性的对象,但它不具有原型而且不能通过JavaScript代码直接访问。创建完活动对象后,把活动对象添加到a的作用域链的最顶端。此时a的作用域链包含了两个对象:a的活动对象和window对象。
下一步是在活动对象上添加一个arguments属性,它保存着调用函数a时所传递的参数。
最后把所有函数a的形参和内部的函数b的引用也添加到a的活动对象上。在这一步中,完成了函数b的的定义,因此如同第3步,函数b的作用域链被设置为b所被定义的环境,即a的作用域。
到此,整个函数a从定义到执行的步骤就完成了。此时a返回函数b的引用给c,又函数b的作用域链包含了对函数a的活动对象的引用,也就是说b可以访问到a中定义的所有变量和函数。函数b被c引用,函数b又依赖函数a,因此函数a在返回后不会被GC回收。
当函数b执行的时候亦会像以上步骤一样。因此,执行时b的作用域链包含了3个对象:b的活动对象、a的活动对象和window对象,如下图所示:
As shown in the figure, when accessing a variable in function b, the search order is:
First search for its own active object, and return if it exists. If it does not exist, it will continue to search for the active object of function a, and search in sequence. Until you find it.
If function b has a prototype prototype object, it will first search for its own prototype object after searching for its own active object, and then continue to search. This is the variable lookup mechanism in Javascript.
If it cannot be found in the entire scope chain, undefined is returned.
Summary, two important words are mentioned in this paragraph: the definition and execution of functions. The article mentions that the scope of a function is determined when the function is defined, not when it is executed (see steps 1 and 3). Use a piece of code to illustrate this problem:
function f(x ) {
var g = function () { return x; }
return g;
}
var h = f(1);
alert(h());
The variable h in this code points to the anonymous function in f (returned by g).
Assuming that the scope of function h is determined by executing alert(h()), then the scope chain of h at this time is: h's active object ->alert's active object->window object.
Assume that the scope of function h is determined when it is defined, which means that the anonymous function pointed to by h has its scope determined when it is defined. Then during execution, the scope chain of h is: h's active object ->f's active object->window object.
If the first assumption is true, the output value is undefined; if the second assumption is true, the output value is 1.
The running results prove that the second hypothesis is correct, indicating that the scope of the function is indeed determined when the function is defined.
4. Application scenarios of closures Protect the safety of variables within functions. Taking the initial example as an example, i in function a can only be accessed by function b and cannot be accessed through other means, thus protecting the security of i.
Maintain a variable in memory. Still as in the previous example, due to closure, i in function a always exists in memory, so every time c() is executed, i will be incremented by 1.
Implement JS private properties and private methods by protecting the security of variables (cannot be accessed externally)
Private properties and methods cannot be accessed outside the Constructor
function Constructor(...) {
var that = this;
var membername = value;
function membername(...) {...}
}
The above three points are the most basic application scenarios of closures, and many classic cases originate from this.
5. Javascript’s garbage collection mechanism
In Javascript, if an object is no longer referenced, then the object will be recycled by the GC. If two objects refer to each other and are no longer referenced by a third party, then the two objects that refer to each other will also be recycled. Because function a is referenced by b, and b is referenced by c outside a, this is why function a will not be recycled after execution.
6. Conclusion
Understanding JavaScript closures is the only way to become an advanced JS programmer. Only by understanding its interpretation and operation mechanism can you write safer and more elegant code.