The interview will be asked closure

/ * 
1, the concept of the closure

the closure can refer to a function of another function has access to scope variables, or simply understood as a defined function within the function;

** /

/ **
2, closure characteristics of

a, function nested function
B, function internal reference an external function parameters and variables
B, parameters and variables are not recycling garbage collection

** /

/ **
disadvantages 3, closure

advantages:
① the protection function variable security and realize the package to prevent the inflow of other environment variable name clashes
② maintain a variable in memory, the cache can be done (but using much the same time is also a drawback, memory consumption)
③ self-executing anonymous function can reduce memory consumption

disadvantages :
① referenced private variable can not be destroyed, increased memory consumption, causing memory leaks, the solution is to manually assign it to null after using variable;
② Second, because of closures involving cross-domain access, it will lead to loss of performance, we can put in a local variable, and then directly access local variable cross-scoped variables to store, to alleviate the shadow of execution speed by ;
** /

/ **
4, which closure scenarios?

① timers transfer Closure of
the first function // setTimeout native rub mixed with parameters not mention
the setTimeout (function (A) {
Alert (A)
}, 1000)
// closure may be achieved by the effect of parameter passing
function B (A) {
return function () {
Alert (A);
}
}
var F B = (. 1);
the setTimeout (F, 1000);

② closure of the setTimeout
for (var I = 0; I <. 5; I ++) {
the setTimeout (function () {
the console.log (I). 5 // Ci. 5
}, 100)
}
the let var is changed to a solution
Second solution of :
// the following code, corresponding to the timer started simultaneously 3, i * 100 for four timers are provided with different time and start, but different execution times, each timer interval is 100 milliseconds, to achieve every time the printing is performed on the effect of 100 milliseconds.
for (var I = 0; I <. 5; I ++) {
(function (I) {
the setTimeout (function () {
the console.log (I)
}, I * 100)
}) (I)
}

③ Bind click event loop node
var Li = document.getElementById ( 'Li');
for (var I = 0; I <li.length ; I ++) {
li [I] .onclick = function () {
Alert (I); // li result of the pop-up length
}
}

solution one: the let to the var;
Second solution:
for (I = 0 var ; i <li.length; i ++) {
Li [i] = .onclick function (NUM) {
return function () {// closure
alert (num); // num is the corresponding value of i
}
}
}
* /

Please refer to more specific chestnutshttps://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures

Guess you like

Origin www.cnblogs.com/fmixue/p/12353418.html