Closure concept
Only a child function inside a function can read a local variable, so a closure can be understood as "a function defined inside a function". In essence, closures are bridges that connect functions inside and outside of functions
Example
function outer(){ var localVal = 30; return localVal;}outer();//30function outer(){ var localVal = 30; return function() { return localVal; }}var func = outer();func();//30
Function: For example, to nest a function in a function, a closure allows the nested function to access the local variables of the function that wraps it.
Packaging
(function(){ var _userId = 123; var _typeId = ‘item‘; var export = {}; function converter(userId){ return + userId; } export.getUserId = function(){ return converter(_userId); } export.getTypeId = function(){ return _typeId; } window.export = export;})();export.getUserId();//123export.getTypeId();//itemexport._uerId;//undefinedexport._typeId;//undefinedexport.converter;//undefined
Closure traps
var tasks = [];for (var i=0; i<3; i++) { tasks.push(function() { console.log(‘>>> ‘ + i); });}console.log(‘end for.‘);for (var j=0; j<tasks.length; j++) { tasks[j]();}
The output is 3. The reason for this problem is that the function is not executed at the time it was created, so we print end for. Before executing the function, because the function references the loop variable i, and I is scoped to the entire function, not the loop, and when the function executes, the value of I becomes 3.
Workaround
Then create a function that passes the loop variable as a function parameter:
var tasks = [];for (var i=0; i<3; i++) { var fn = function(n) { tasks.push(function() { console.log(‘>>> ‘ + n); }); }; fn(i);}//简化语法,直接用匿名函数的立即执行模式(function() { ... })()var tasks = [];for (var i=0; i<3; i++) { (function(n) { tasks.push(function() { console.log(‘>>> ‘ + n); }); })(i);}
Summarize
Advantages: Flexible and convenient, package
Cons: Wasted space, memory leaks, performance consumption
JavaScript functions (three)--closures and scopes