Closure _ JavaScript in javascript

Source: Internet
Author: User
The official explanation of closures is: an expression (usually a function) with many variables and an environment bound to these variables ), therefore, these variables are part of the expression. 1. What is a closure?

The official explanation of closures is: an expression (usually a function) that has many variables and an environment bound to these variables, so these variables are part of the expression.

Simply put, Javascript allows the use of internal functions-that is, function definitions and function expressions are located in the body of another function. In addition, these internal functions can access all the local variables, parameters, and other declared internal functions declared in their external functions. When one of these internal functions is called outside the external functions that contain them, a closure is formed.

Features of closures

1. nested Functions

2. The function can reference external parameters and variables.

3. Parameters and variables are not recycled by the garbage collection mechanism.

Generally, after the function is executed, the partial activity object is destroyed, and only the global scope is saved in the memory. But the closure is different!

Function fn () {var a =; function fn () {// you can access the value defined in fn alert (a ++) ;}fn ();} fn (); // function fn () {var a =; function fn () {// you can access alert (a ++);} return fn; //} var f = fn (); f (); // after execution, a is still in memory f (); // f = null; // a is recycled

The above is a small Editor to introduce you to the closure in JavaScript, I hope to help you!

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.