When are Javascript closures recycled?

Source: Internet
Author: User

Defined

Closures are a combination of functions and the lexical context in which the function is declared.
Closures are functions that have access to variables in another function scope, and the most common way to create closures is to create another function within one function and access the local variables of the function through another function.

Example

 function   Fntest (_i) { var  i = _i;  function   Fnadd () {Console.log (i  + +)     return   Fnadd;}  var  fun = fntest (100  // 100,i resident memory   fun ();  // 101,i resident memory   fun ();  // 102,i resident memory   Fun=null ;  //I was recycled by GC   

The principle of JavaScript garbage collection

1. In JavaScript, if an object is no longer referenced, the object will be recycled by GC;
2. If two objects are referenced by each other, but are not referenced by a third party, then these two mutually referenced objects are recycled.

Closure benefits

1. A variable can reside in memory for a long time
2. Simulate private methods to avoid contamination by global variables
In object-oriented programming languages, such as Java, methods are allowed to be declared private, meaning that they can only be called by other methods in the same class.
JavaScript does not have this native support, but we can use closures to emulate private methods. Private methods are not only useful for restricting access to code: It also provides the power to manage the global namespace, avoiding the non-core approach of confusing the public interface portion of the code.

Closures Disadvantages

Resident memory increases memory usage and is prone to memory leaks due to improper use.

When are Javascript closures recycled?

Manually delete a closed instance that is no longer in use

Resources

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures
Https://www.cnblogs.com/wangyingblog/p/5569745.html

When are Javascript closures recycled?

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.