Simple Application of JavaScript closure, javascript Closure

Source: Internet
Author: User
Tags closure definition

Simple Application of JavaScript closure, javascript Closure

Closure Definition

In JavaScript, when an internal function is referenced by a variable other than its external function, a closure is formed. In short, closures are functions that can read internal variables of other functions.

Function of closure:

1. Read the internal variables of the function.
2. Keep the values of these variables in the memory.
Simple Application of closures

Example 1:

Function a () {var I = 0; function B () {console. log (++ I);} return B;} var c = a (); // After var c = a () is executed, variable c points to function B, after executing c (), the I value (1) is displayed ). C (); // output 1

Example 2:

(Function () {var I = 0; return function () {console. log (++ I) ;}}) (); // output 1

Example 3:

(Function (I) {return function () {console. log (++ I) ;}}) (0) (); // output 1

Example 4:

For (var I = 0; I <3; I ++) {setTimeout (function (I) {return function () {console. log (I) ;};}) (I), 2000); console. log (I + 10);} // output 10 11 12 (two seconds later) 0 1 2

Example 5:

For (var I = 0; I <3; I ++) {setTimeout (function (I) {return function () {console. log (I) ;};}) (I) (), 2000); console. log (I + 10);} // output 0 10 1 11 2 12 immediately (the program stops running in two seconds)

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.