JavaScript in a closed package

Source: Internet
Author: User

What is a closure package

The "official" explanation is that the so-called "closure" refers to an expression (usually a function) that has many variables and an environment in which these variables are bound, and therefore these variables are also part of the Expression.

Closure Code:

function A () {  var i=0;  Function b () {   alert (+ +i);     } return b;} var c=a (); c ();

There are two features of this code:

1. Function b is nested inside function a;

2. Function A returns function b;

So after the execution of Var c=a (), the variable c actually points to function b, after executing c () will pop up a window to show the value of I (the first time is 1), This short code creates a closure, why? Because the variable C outside of function A refers to function B in function a, that is:

when function A's intrinsic function B is referenced by a variable outside of function a, a closure is Created.

Defined:

If in an intrinsic function a reference is made to a variable outside the scope (but not at the global scope), then the intrinsic function is considered a closure.

Application Scenarios:

1. Security of variables within the protection Function. Function A can be accessed only by Function B and cannot be accessed by other means, thus protecting the security of I.

2. Maintains a variable in memory. Because of the closure, function A in I always exists in memory, so every time I execute C (), I will add 1.

JavaScript in a closed package

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.