前端面试宝典---闭包

闭包介绍

使用闭包:

  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);
    
相关推荐
VT.馒头3 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
css趣多多4 小时前
一个UI内置组件el-scrollbar
前端·javascript·vue.js
C澒4 小时前
前端整洁架构(Clean Architecture)实战解析:从理论到 Todo 项目落地
前端·架构·系统架构·前端框架
C澒4 小时前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
Charlie_lll4 小时前
学习Three.js–雪花
前端·three.js
onebyte8bits4 小时前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒4 小时前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC5 小时前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得05 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice5 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js