前端面试宝典---闭包

闭包介绍

使用闭包:

  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);
    
相关推荐
新时代农民工Top15 分钟前
React + JavaScript 实现可拖拽进度条
前端·javascript·react.js
9ilk1 小时前
【前端基础】--- HTML
前端·html
Lafar1 小时前
Dart单线程怎么保证UI运行流畅
前端·面试
不和乔治玩的佩奇1 小时前
【 设计模式】常见前端设计模式
前端
bloxed1 小时前
vue+vite 减缓首屏加载压力和性能优化
前端·vue.js·性能优化
打野赵怀真1 小时前
React Hooks 的优势和使用场景
前端·javascript
HaushoLin1 小时前
ERR_PNPM_DLX_NO_BIN No binaries found in tailwindcss
前端·vue.js·css3·html5
Lafar2 小时前
Widget 树和 Element 树和RenderObject树是一一 对应的吗
前端
小桥风满袖2 小时前
炸裂,前端神级动效库合集
前端·css