Use of JavaScript closures

Source: Internet
Author: User

Today, I learned the following JavaScript language, never thought about why to use anonymous and closures, for JS local variables and the concept of global understanding is not deep, consider the following code:

JS code function f1 () {var n=999;    Nadd=function () {n+=1} function F2 () {alert (n);  } return F2;  } var result=f1 (); Result ();  999 Nadd (); Result (); 1000


If the variable n is defined as a global variable, it will always be stored in memory, unless the browser is closed, but in some cases we have to use some variables frequently, then the closure method can be used to meet the needs, but it should be noted that:

Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function. Here is a quote from an article on the Web: http://www.jb51.net/article/24101.htm

Use of JavaScript closures

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.