何为闭包

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

根本案例

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

所以,闭包函数必须要被内部变量持有???

例二

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


所以,被包裹的闭包函数是否被内部变量持有并不是造成闭包的条件

例三

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


仍旧造成了闭包,因为闭包作用域是外部所有闭包函数共享的,只有有一个外部函数应用到了内部函数的变量即可造成闭包

所以造成闭包的条件: 存在外部函数应用内部函数中定义的变量

利用场景

防抖和节流

见具体文章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)}

柯里化

概念:把承受多个参数的函数变换成承受繁多参数的函数,并且返回承受余下的参数而且返回后果的新函数的技术

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 岁了, 我喜爱吃 苹果

高级柯里化函数

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...