回调和高阶函数Javascript [英] Callbacks and Higher Order functions Javascript

查看:41
本文介绍了回调和高阶函数Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Eloquent JS第5章中的问题 http://eloquentjavascript.net/05_higher_order.html

This is a problem from chapter 5 of Eloquent JS http://eloquentjavascript.net/05_higher_order.html

function noisy(f) {
  return function(arg) {
     console.log("calling with", arg);
     var val = f(arg);
     console.log("called with", arg, "- got", val);
     return val;
   };
 }
noisy(Boolean)(12);
// → calling with 0
// → called with 0 - got false

有人可以解释f(arg)的意义吗?我的意思是他在另一个参数arg上调用参数f?我很困扰.

Can someone please explain how f(arg) makes sense? I mean he is calling the argument f on another argument arg?? I am very confused.

具有返回值的部分如何?为什么必须在那里?当我删除它时,代码仍然可以正常运行.

How about the part that has return val; Why does that have to be there? When I delete it, the code still runs like it should.

最后,有人可以逐行解释代码解释吗?在示例中,传递布尔值有何意义?

Lastly, can some explain the code interpretation line by line? How does passing boolean make sense in the example?

非常感谢您

推荐答案

基础知识

noisy 将一个功能映射到另一个功能,该功能与原始功能相同,但是将输入和输出值(更确切地说是它们的字符串表示形式)写入控制台.

noisy maps a function to another function that does the same as the original but writes input and output value ( moreprecisely their string representations) to the console.

  • Q1:目的似乎是通过简单的日志记录工具来增强对象构造函数,以显示哪些初始化参数产生哪种对象状态.为此, noisy 返回一个函数对象-通过输出到控制台增强的原始函数.

  • Q1: The intention seems to be the enhancement of object constructors with a simple logging facility to show which initialization arguments produce which kind of object state. To this end, noisy returns a function object - the original function enhanced by output to the console.

Q2:调用增强型 Boolean 构造函数而未分配其返回值.因此,增强的构造函数是否返回值对代码没有影响.

Q2: The enhanced Boolean constructor is called without assigning its return value. Thus it makes no difference to the code whether the enhanced constructor does return a value or not.

Q3: Boolean 揭示了您为不同的初始化参数获得的布尔值.我想要吸取的教训是,数字 0 会为您提供 false ,其他则为 true (后者在我部分,但是使用 noisy ,您可以使用一个工具来检查是否有任意构造函数和初始化值.

Q3: Boolean reveals what boolean values you get for different initialization arguments. I guess the lesson to be learned is that a numerical of 0 gets you a false, anything else true (the latter is informed guessing on my part, but with noisy you have a tool to generically check that for arbitrary constructors and initialization values).

这篇关于回调和高阶函数Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆