前端面试宝典---闭包
闭包介绍
使用闭包:
- 在函数内声明一个变量,避免外部访问
- 在该函数内再声明一个函数访问上述变量(闭包)
- 返回函数内部的函数
- 使用完毕建议闭包函数=null;译放内存
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
let counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
counter = null;
闭包应用场景
在 ES6 引入 let 和 const 之前,JavaScript 没有块级作用域,只有函数作用域。可以使用闭包来模拟块级作用域。以下是一个经典的循环中使用闭包的例子:
// 不使用闭包的情况
function printNumbersWithoutClosure() {
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
}
// 使用闭包的情况
function printNumbersWithClosure() {
for (var i = 0; i < 5; i++) {
(function (index) {
setTimeout(function () {
console.log(index);
}, index * 1000);
})(i);
}
}
// 测试不使用闭包的情况
console.log('不使用闭包的情况:');
printNumbersWithoutClosure();
// 测试使用闭包的情况
setTimeout(function () {
console.log('使用闭包的情况:');
printNumbersWithClosure();
}, 5000);