JavaScript memory leaks

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.