参数来自哪里?

Isa*_*aac 5 javascript functional-programming arrow-functions

function createMathOperation(operator) {
  console.log(operator); //(augend, addend) => augend + addend
  return (value, other) => {
    return operator(value, other)
  }
}

const add = createMathOperation((augend, addend) => augend + addend)

add(1,2)//3
Run Code Online (Sandbox Code Playgroud)

我找到了上面的函数定义lodash.我试图理解它,但无济于事.

在内部createMathOperation,我尝试记录operator,这是值

(augend, addend) => augend + addend
Run Code Online (Sandbox Code Playgroud)

我想valueother12,但怎么样?

而如何return operator(value, other)在工作operator(augend, addend) => augend + addend

任何人都可以将其转换为更长的人类可读形式,以便更好地理解吗?

Tit*_*mir 4

这是函数式编程的本质,您可以传入一个函数,返回一个函数,然后调用作为参数收到的函数:

function createMathOperation(operator) {
  console.log(operator); // This is a the function that performs the computation 
  // We return a new function (using arrow syntax) that receives 2 arguments and will call the original operator we passed in to createMathOperation
  // The code inside this function is not executed here, the function is not invoked. 
  // The caller can take the returned function and executed 0-n times as they wish. 
  return (value, other) => { 
    // when we invoke add this is the code that gets called and the arguments we pass to add end up in value and other
    console.log("Getting ready to compute " + value + " operator " + other); 
    return operator(value, other) // since operator is a function we just invoke it as we would any other function with the two arguments we got from whoever called us.
  }
}

// add will contain the wrapped function that has our extra console.log 
const add = createMathOperation((augend, addend) => augend + addend)

// The 'Getting ready ...' text has not been printed yet, nobody invoked the function that was returned yet, the next line will do so.
console.log(add(1,2)) 
// will output:
// Getting ready to compute 1 operator 2
// 3
Run Code Online (Sandbox Code Playgroud)

的注释=>只是function表达式上的语法糖,它在 周围有额外的语义this,但对于这个例子来说,(augend, addend) => augend + addend相当于function (augend, addend){ return augend + addend; }