闭包

何为闭包

一个函数包裹另外一个函数,被包裹的函数成为闭包函数,外部函数为闭包函数提供了一个闭包做用域???segmentfault

基本案例

function outer() {
    let bar = 'foo'
    function inner() {
        debugger
        console.log(bar) // 闭包函数用到了外部函数的变量bar
    }
    return inner
}
let foo = outer() // 执行外部函数返回内部函数
foo()  // 执行内部函数

image.png

因此,闭包函数必需要被外部变量持有???数组

例二

function outer() {
    let bar = 'foo'
    function inner() {
        debugger
        console.log(bar)
    }
    inner() // 直接在外部函数中执行了闭包函数inner
}
outer()

image.png
因此,被包裹的闭包函数是否被外部变量持有并非造成闭包的条件闭包

例三

function outer() {
    let bar = 'foo'
    function inner() {
        console.log(bar)
    }
    function hello() {
        // hello没有使用外部outer函数的变量
        debugger
    }
    hello() 
}
outer()

image.png
依旧造成了闭包,由于闭包做用域是内部全部闭包函数共享的,只要有一个内部函数使用到了外部函数的变量便可造成闭包app

因此造成闭包的条件: 存在内部函数使用外部函数中定义的变量

应用场景

防抖和节流

见具体文章https://segmentfault.com/a/11...函数

给元素伪数组添加事件

let li = document.querySelectorAll('li');
for(var i = 0; i < li.length; i++) {
    (function(i){
        li[i].onclick = function() {
            alert(i);
        }
    })(i)
}

柯里化

概念:把接受多个参数的函数变换成接受单一参数的函数,而且返回接受余下的参数并且返回结果的新函数的技术ui

function currying(fn,...res1) {
    return function(...res2) {
        return fn.apply(null, res1.concat(res2))
    }
}
function sayHello(name, age, fruit) {
  console.log(console.log(`我叫 ${name},我 ${age} 岁了, 我喜欢吃 ${fruit}`))
}

const curryingShowMsg1 = currying(sayHello, '小明')
curryingShowMsg1(22, '苹果')            // 我叫 小明,我 22 岁了, 我喜欢吃 苹果

高级柯里化函数this

function curryingHelper(fn, len) {
  const length = len || fn.length  // 第一遍运行length是函数fn一共须要的参数个数,之后是剩余所须要的参数个数
  return function(...rest) {
    return rest.length >= length    // 检查是否传入了fn所需足够的参数
        ? fn.apply(this, rest)
        : curryingHelper(currying.apply(this, [fn].concat(rest)), length - rest.length)        // 在通用currying函数基础上
  }
}

function sayHello(name, age, fruit) { console.log(`我叫 ${name},我 ${age} 岁了, 我喜欢吃 ${fruit}`) }    

const betterShowMsg = curryingHelper(sayHello)
betterShowMsg('小衰', 20, '西瓜')      // 我叫 小衰,我 20 岁了, 我喜欢吃 西瓜
betterShowMsg('小猪')(25, '南瓜')      // 我叫 小猪,我 25 岁了, 我喜欢吃 南瓜
betterShowMsg('小明', 22)('倭瓜')      // 我叫 小明,我 22 岁了, 我喜欢吃 倭瓜
betterShowMsg('小拽')(28)('冬瓜')      // 我叫 小拽,我 28 岁了, 我喜欢吃 冬瓜

缺点

可能会引发内存泄露,具体见https://segmentfault.com/a/11...spa

相关文章
相关标签/搜索