前端面试宝典---闭包

闭包介绍

使用闭包:

  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);
    
相关推荐
weelinking6 小时前
【claude】14_Claude作为技术文档助手
前端·人工智能·react.js·数据挖掘·前端框架
jiayong236 小时前
前端面试题库 - JavaScript核心基础篇
前端·javascript·面试
软件技术NINI6 小时前
泉州html+css 4页
前端·javascript·css·html
再吃一根胡萝卜6 小时前
OpenScreen:免费开源的录屏神器,做出专业级演示视频
前端
Cloud_Shy6186 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十一章 Python 包跟踪器 下篇)
前端·后端·python·数据分析·excel
kyriewen6 小时前
我用AI把公司10万行代码屎山重构了,CTO看了代码后说:你提前转正
前端·javascript·ai编程
ttwuai6 小时前
XYGo Admin 菜单与路由:Vue3 动态路由 + GoFrame 权限菜单的完整实现方案
前端·vue·后台框架
程序员码歌6 小时前
OpenSpec 到 Superpowers:AI 编码从说清到做对
android·前端·人工智能
爱编程的小新☆6 小时前
LangGraph4j工作流框架
前端·数据库·ai·langchain·langgraph4j