前端面试宝典---闭包

闭包介绍

使用闭包:

  1. 在函数内声明一个变量,避免外部访问
  2. 在该函数内再声明一个函数访问上述变量(闭包)
  3. 返回函数内部的函数
  4. 使用完毕建议闭包函数=null;译放内存
typescript 复制代码
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 没有块级作用域,只有函数作用域。可以使用闭包来模拟块级作用域。以下是一个经典的循环中使用闭包的例子:

typescript 复制代码
// 不使用闭包的情况
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);
    
相关推荐
li357417 分钟前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj40 分钟前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel1 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel1 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
西陵2 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld2 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
东风西巷4 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求
萌萌哒草头将军4 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
半夏陌离4 小时前
SQL 入门指南:排序与分页查询(ORDER BY 多字段排序、LIMIT 分页实战)
java·前端·数据库