参数来自哪里?

时间:2018-05-22 07:54:46

标签: 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

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

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

(augend, addend) => augend + addend

我猜valueother12但是怎么样?

return operator(value, other)operator

时,(augend, addend) => augend + addend的工作原理

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

3 个答案:

答案 0 :(得分: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

关于=>的注释只是function表达式上的语法糖,它在this附近有额外的语义,但对于此示例,(augend, addend) => augend + addend等同于{{ 1}}

答案 1 :(得分:1)

createMathOperation返回函数,它会添加两个数字。这是更易阅读的版本:

function createMathOperation(fn) {
  console.log(fn);
  return function(value, other){
    return fn(value, other);
  };
}

const add = createMathOperation(function (augend, addend) {
  return augend + addend;
});

add(1,2)//3

我将'operator'重命名为'fn'以减少混淆(由于某种原因,语法高亮显示为蓝色)。

答案 2 :(得分:0)

你在古老的JS中的代码看起来像:

var createMathOperation = function(operator) {
  // operator is scope-locked within this operation wrapper
  console.log('operator:', operator);
  return function(value, other) {
    // The wrapper returns an anonymous function that acts as a call-wrapper
    // for your original function
    console.log('value:', value);
    console.log('other:', other);
    return operator(value, other)
  }
}

var add = createMathOperation(function(augend, addend) {
  // This is what is being called at line 9 - return operator(value, other)
  return augend + addend;
});

console.log('result 1+2:', add(1,2));

一般情况下,我认为所有这些都没有多大用处,你可以const add = (a, v) => a + v;做同样的结果。