【问题标题】:How to reuse a closure function assigning it to a variable or constant in JavaScript如何重用闭包函数,将其分配给 JavaScript 中的变量或常量
【发布时间】:2022-06-15 05:52:36
【问题描述】:

我正在解决一个旨在使用闭包的练习。您必须创建一个函数,该函数返回一个存储值的函数,并且在您重用它时,将新值添加到已保存的值中。

const firstValue = myFunction(3);
const secondValue = firstValue(4);
// result => 7

这是我用来练习闭包的代码:

function addNumbers(num) {
    let storage = 0
    let n = num
    function adding(n) {
        storage += n;
        return storage
    }
    return adding(n)
}

let firstAttemp = addNumbers(4)
let secondAttemp = firstAttemp(3)

console.log(firstAttemp)

这会抛出一个错误“Uncaught TypeError: firstAttemp is not a function”

【问题讨论】:

    标签: javascript function scope closures reusability


    【解决方案1】:
    const addNumbers = (a) => (b) => a + b
    

    这叫做柯里化,更多细节here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多