函数作为参数发送给其他函数

时间:2019-02-16 16:33:19

标签: javascript functional-programming

遇到此问题时,我正在阅读一本有关react的书,并且在函数编程一章中。

const insideFn = logger =>
    logger("They can be sent to other functions as arguments");
insideFn(message => console.log(message))
// They can be sent to other functions as arguments

现在我很困惑:

  1. insideFn的输出是logger函数的参数,仅是一个参数,不会从logger函数返回。那么为什么insideFn的输出,logger的参数呢?
  2. 我尝试检查message的类型-结果为字符串。为什么是字符串? message不是函数吗?
  3. 我希望在处理console.log条消息时,它应该返回logger的函数定义,但是它返回其参数?这对我来说没有道理?

感谢您的解释。

1 个答案:

答案 0 :(得分:2)

箭头功能使它有些混乱。也许更详细的例子会更清楚:

function insideFn(logger) {
    logger("inside's log message");
    // some computation here
    return 42;
}

function myLogger(message) {
    console.log(message);
}
insideFn(myLogger);