gpt4 book ai didi

javascript - Eloquent JavaScript,第 2 版,第 5 章高阶函数

转载 作者:行者123 更新时间:2023-11-29 17:01:14 24 4
gpt4 key购买 nike

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

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 val = f(arg); 的行。

有人可以指导我完成那行代码吗?你如何将一个论点传递给另一个论点?我不确定我是否使用了正确的术语,所以如果我用错了请原谅。我只是不明白这一行,也无法轻易找到关于这个主题的任何其他话题。

谢谢!

最佳答案

noisy 是一个函数,它引用另一个函数 f 并返回一个包装了 f 的新函数,以便调用并返回值记录到控制台。

val 是函数 f 被调用的结果,其中 f 是函数引用,当 noisy 被调用。

一步一步来:

// 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);

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

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

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

关于javascript - Eloquent JavaScript,第 2 版,第 5 章高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27934951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com