【发布时间】:2020-07-10 23:43:14
【问题描述】:
我正在创建一个函数 saveOutput,它接受一个函数和一个字符串。然后saveOutput 将返回一个行为与传入函数完全相同的函数,除非密码字符串作为参数传入。发生这种情况时,返回的函数将返回一个对象,其中所有先前传入的参数作为键,相应的输出作为值。
我认为下面的代码是正确的,但是当我运行我的代码时遇到了Range Error: Maxiumum call stack size exceeded。
function saveOutput(inputFunc, string) {
let obj = {};
//inputFunc() accepts one args
//string like a pwd
return function inputFunc(input) {
if (input === string) {
return obj;
} else {
obj[input] = inputFunc(input);
return inputFunc(input);
}
}
//returns a fxn
return inputFunc;
}
//Test cases
const multiplyBy2 = function(num) { return num * 2; };
const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
console.log(multBy2AndLog(2)); // should log: 4
console.log(multBy2AndLog(9)); // should log: 18
console.log(multBy2AndLog('boo')); // should log: { 2: 4, 9: 18 }
【问题讨论】:
-
你通过定义一个同名的函数来隐藏参数
inputFunc。只使用return function (input) { .. },或者,如果你想给这个函数一个名字,可以使用任何其他的名字。
标签: javascript closures higher-order-functions