Eloquent JavaScript,第2版,第5章高阶函数 [英] Eloquent JavaScript, 2nd Edition, Chapter 5 Higher-Order Functions

查看:69
本文介绍了Eloquent JavaScript,第2版,第5章高阶函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,我希望在第二版中获得第5章的帮助。 Eloquent JavaScript。具体来说,我遇到了以下示例:

I'm very new to JavaScript, and I was hoping to get some help with Chapter 5 in the 2nd Ed. of Eloquent JavaScript. Specifically, I ran into the example below:

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)(0);
// → calling with 0
// → called with 0 - got false



<我认为我理解产生其他功能的高阶函数的概念,但我不确定我是否理解捕获的概念以及它在这里的意义。具体来说, var = f(arg); 的行

有人可以带我走过那条线代码?你如何将论证传递给另一个论点?我不确定我是否使用了正确的术语,所以如果我弄错了,请原谅。我只是不明白这一行,并且不能轻易找到关于这个主题的任何其他主题。

Can someone please walk me through that line of code? How do you pass an argument to another argument? I'm not sure if I'm using the correct terminology, so please excuse me if I've got it wrong. I just don't understand that line and couldn't easily find any other threads about this subject.

谢谢!

推荐答案

嘈杂是一个引用另一个函数的函数 f 并返回一个包含 f 的新函数,以便将其调用和返回值记录到控制台。

noisy is a function that takes a reference to another function f and returns a new function that wraps f so that it's call and return values are logged to the console.

val 是调用函数 f 的结果,其中 f 是在调用 noisy 时传递的函数引用。

val is the result of the function f being called, where f is a function reference that is passed when noisy is called.

一步一步走:

// noisy accepts argument f (where f itself appears to be a function)
function noisy(f) {
    // noisy returns a new function that takes an argument arg
    return function(arg) {
        // when this new function is called, it logs to console
        console.log("calling with", arg);
        // the function you originally passed to noisy is now called, with the return value stored in val
        var val = f(arg);
        // return value val also logged to console
        console.log("called with", arg, "- got", val);
        // return value val is returned from the generated function
        return val;
    };
}
// noisy is called with the inbuilt function Boolean and the argument 0 (to test the boolean value of 0)
noisy(Boolean)(0);

另一个用例可能是这样的:

Another use case could be something like this:

function someFuncToMonitor(someArg) {
    return someArg + 1;
}
monitoredFunc = noisy(someFuncToMonitor);
result = monitoredFunc(5);
// calling with 5
// calling with 5 - got 6

因此,简而言之,调用 monitoredFunc 为您调用 someFuncToMonitor 函数,并告诉您有关调用和结果的信息。

So in short calling monitoredFunc calls your someFuncToMonitor function for you and tells you about the call and the results.

这篇关于Eloquent JavaScript,第2版,第5章高阶函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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