前端面试宝典---闭包

闭包介绍

使用闭包:

  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);
    
相关推荐
bearpping1 小时前
Nginx 配置:alias 和 root 的区别
前端·javascript·nginx
@大迁世界1 小时前
07.React 中的 createRoot 方法是什么?它具体如何运作?
前端·javascript·react.js·前端框架·ecmascript
January12071 小时前
VBen Admin Select 选择框选中后仍然显示校验错误提示的解决方案
前端·vben
. . . . .1 小时前
前端测试框架:Vitest
前端
xiaotao1312 小时前
什么是 Tailwind CSS
前端·css·css3
战南诚3 小时前
VUE中,keep-alive组件与钩子函数的生命周期
前端·vue.js
发现一只大呆瓜3 小时前
React-彻底搞懂 Redux:从单向数据流到 useReducer 的终极抉择
前端·react.js·面试
霍理迪3 小时前
Vue的响应式和生命周期
前端·javascript·vue.js
李剑一3 小时前
别再瞎写了!Cesium 模型 360° 环绕,4 套源码全公开,项目直接用
前端