當函數作為參數傳入函數,該函數為高階函數妓局,當函數作為函數的返回結果返回总放,就形成了閉包。返回的函數被引用好爬,該引用就保留了定義時的詞法作用域局雄,即該引用就是閉包。
1.函數作為返回值
'use strict'
function foo () {
var attr = [];
for(var i = 0; i < 10; i++){
attr.push(function(){
return i;
});
}
return attr;
}
var r = foo();
console.log(r[0]()); //10
console.log(r[1]()); //10
console.log(r[2]()); //10
改造1:
'use strict'
function foo () {
var attr = [];
for(let i = 0; i < 10; i++){
attr.push(function(){
return i;
});
}
return attr;
}
var r = foo();
console.log(r[0]()); //0
console.log(r[1]()); //1
console.log(r[2]()); //2
改造2:
'use strict'
function foo () {
var attr = [];
for(var i = 0; i < 10; i++){
attr.push(function(n){
return function(){
return n;
}
}(i));
}
return attr;
}
var r = foo();
console.log(r[0]());
console.log(r[1]());
console.log(r[2]());
2.返回對象攜帶閉包
'use strict';
function create_counter(initial) {
var x = initial || 0;
return {
inc: function () {
x += 1;
return x;
}
}
}
var c1 = create_counter();
c1.inc(); // 1
c1.inc(); // 2
c1.inc(); // 3
注意:對象中產生閉包存炮,對象返回