The closure problem in JS

Source: Internet
Author: User

Closure: Special grammatical phenomena of local variables can also be used outside the function
Global variables VS Local variables:
Global variables: Benefits: shareable, reusable;
Cons: Can be arbitrarily modified at any location-global pollution
Local Variables: Benefits: Security
Cons: Not shareable, non-reusable
When to use closures: that is, share local variables, and do not want to tamper with random.
Ii. Building a closure structure: 3 steps:
1. Encapsulating protected local variables using the outer function
2. Inside the outer function, define the inner function that specifically operates the local variable * and return *.
3. In the global call to the outer function, get the inner function of the object, saved in the global variable used repeatedly.

Three, closure three characteristics:
1. Nesting functions
2. The inner function uses the local variables of the outer function
3. The inner function object is returned to the outside, and is called repeatedly at the global level

Iv. the role of closures: protecting shareable local variables
* How to quickly determine the output of the closure function: *
1. The outer function was called several times and there were several protected local variables

Five, classic questions

1.

Function F1 () {
var n=999;
Nadd=function () {n+=1}
function F2 () {alert (n);}
return F2;
}
var result=f1 ();
Result ();
Nadd ();
Result ();
2.

function Fun1 () {
var arr=[];

for (var i=0;; i<3;i++) {
Arr[i]=function () {return i};
}
I=3
return arr;
/*
function () {return i}
function () {return i}
function () {return i}
*/
}
var arr=fun1 (); Closure one Create i=3
Console.log (Arr[0] ()); 3
Console.log (Arr[1] ()); 3
Console.log (Arr[2] ()); 3

3.

var Getsecret,setsecret;
(function () {
var secret=0;
Getsecret=function () {
Return secret;
}
Setsecret=function (sec) {//var function Setsecret (sec) {}
Secret=sec;
}
})();
window.secret=100;
Console.log (Getsecret ()); 0
Setsecret (55);
Console.log (Getsecret ()); 55

The closure problem in JS

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.