根据 MDN:“闭包是捆绑在一起(封闭)的函数及其周围状态(词法环境)的引用的组合 。换句话说,闭包使您可以从内部函数访问外部函数的作用域 。在 JAVAScript 中,每次创建函数时都会创建闭包 。”什么是闭包?

文章插图
根据 MDN:“闭包是捆绑在一起(封闭)的函数及其周围状态(词法环境)的引用的组合 。换句话说,闭包使您可以从内部函数访问外部函数的作用域 。在 JavaScript 中,每次创建函数时都会创建闭包 。”
例如:
const getShowName = () => {const name = "fatfish" // name is a local variable created by getShowNamereturn () => {console.log(name) // use variable declared in the parent function}}const showName = getShowName()showName() // fatfish作为前端开发工程师,我们在很多场景中都会用到它,它的功能确实很强大 。1. 解决循环中的问题
for (var i = 0; i < 3; i++) {setTimeout(() => {console.log(i) // What will i print out?}, 1000 * i)}我们怎样才能让它打印0、1、2呢?是的,你可以使用闭包来解决这个问题 。它很快就会打印出 0、1 和 2 。
for (var i = 0; i < 3; i++) {((n) => {setTimeout(() => {console.log(n) // What will i print out?}, 1000 * n)})(i)}当然,我们还有另一种更简单的方法,只需将var替换为let即可解决这个问题 。for (let i = 0; i < 3; i++) {setTimeout(() => {console.log(i) // What will i print out?}, 1000 * i)}2.记忆功能利用闭包的特性,我们可以减少计算量,提高我们编写的程序的性能 。const memoize = (callback) => {const cache = new Map()return function (n) {if (cache.has(n)) { // When it already exists in the cache, the result will be returned directly, we don't need to calculate it agAInreturn cache.get(n)} else {const res = callback.call(this, n)cache.set(n, res) // After the first calculation, the result will be cachedreturn res}}}const fibonacci = memoize(function fib (n) {if (n === 1) {return 1}if (n === 2 || n === 3) {return 2}return fib(n - 1) + fib(n - 2)})console.log(fibonacci(1)) // 1console.log(fibonacci(10)) // 68console.log(fibonacci(10)) // 68 Read from cache instead of computing again3. 封装私有变量和属性很早以前,我们经常通过闭包来实现对私有变量的保护 。我们只能通过getName和setName来获取和设置_name的值 。
这样我们就可以有效防止_name被恶意修改 。
const createName = (name) => {let _name = namereturn {getName () {return _name},setName (name) {_name = name}}}const p = createName('fatfish')p.getName() // fatfishp.setName('medium')p.getName() // medium4.函数柯里化作为一名前端开发工程师,我相信你已经了解了什么是函数柯里化 。让我们尝试使用闭包来实现它 。const curry = (callback, ...args) => {return function (...innerArgs) {innerArgs = args.concat(innerArgs)if (innerArgs.length >= callback.length) {return callback.Apply(this, innerArgs)} else {return curry(callback, innerArgs)}}}const add = curry((a, b, c) => {return a + b + c}, 1)console.log(add(2, 3)) // 6太好了,我们做到了,那你还知道闭包的其他用途吗?【四个关于 JavaScript 中闭包的有用技巧】
推荐阅读
- 关于接口测试,你了解多少?
- 有文采典故的女孩名字大全四个字 有文采典故的女孩名字大全
- 十个很少使用的 JavaScript Console 方法
- 八个针对高级职位的高级 JavaScript 面试题
- 关于感情的句子有哪些
- 关于生姜不得不说的偏方
- 感冒能吃鸡蛋吗 10个关于鸡蛋的小常识
- 罗云熙增重四个月,颜值重回巅峰!让观众直呼梦回《香蜜》时期
- 好听的男生名字古风四个字 好听的男生名字古风
- 财运旺的公司名字大全四个字 财运旺的公司名字
