1, what is closure, and closures involved in the scope of the chain here is not said.
2. JavaScript garbage collection mechanism
JavaScript does not need to manually free memory, it uses an automatic garbage collection mechanism (garbage collection). When an object is useless, that is, the object is not referenced in the program, the variable is released from memory.
var s = [ 1, 2 ,3];
var s = null;
//这样原始的数组[1 ,2 ,3]就会被释放掉了。
3. Circular Reference
Three objects A, B, C
A property of a aàbàc:a refers to B, and C is also referenced by the properties of B. If you clear a, then B, C is also released.
Aàbàcàb: This adds a property of C to the reference B object, and if this is clear a, then B, C is not released, because a circular reference is generated between B and C.
var a = {};
a.pro = { a:100 };
a.pro.pro = { b:100 };
a = null ;
//这种情况下,{a:100}和{b:100}就同时也被释放了。
var obj = {};
obj.pro = { a : 100 };
obj.pro.pro = { b : 200 };
var two = obj.pro.pro;
obj = null;
//这种情况下 {b:200}不会被释放掉,而{a:100}被释放了。
4. Circular references and closures
function outer(){
var obj = {};
function inner(){
//这里引用了obj对象
}
obj.inner = inner;
}
This is a circular reference that is hidden from the other. When outer is invoked, the obj and inner two objects are created inside it, and the inner property of obj references inner; Also, the inner references obj, because obj is still in the Innerfun closed environment. This is precisely due to JavaScript-specific "scope chaining".
As a result, closures are very easy to create circular references, and fortunately JavaScript can handle this circular reference well.