我正面临以下挑战描述:
“编写一个函数,一旦接受回调作为输入并返回一个函数。当第一次调用返回的函数时,它应该调用回调并返回该输出。如果它被调用任何额外的时间,而不是调用再次回调它将从第一次调用“
时返回输出值给你的代码是:
function addByX(x) {
return function(num) {
return num + x;
};
}
var addByTwo = addByX(2);
function once(func) {
// ADD CODE HERE
}
var onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
console.log(onceFunc(9001)); //should log 6
我可以让代码返回你期望的内容(6,12,9003),但是我无法让它继续记录6. onceFunc本身等于addByTwo,x等于2,所以传递任何数字into onceFunc充当n。我是否需要将第一次返回6或n = 4保存到变量中?
答案 0 :(得分:2)
可能有更好的解决方案,但这就是我想出的。我尝试在代码中添加注释来解释它正在做什么,但如果您有任何其他问题,请告诉我:https://jsfiddle.net/nvd9dqza/6/
function addByX(x) {
return function(num) {
return num + x;
};
}
var addByTwo = addByX(2);
function once(func) {
// a variable which is scoped to the "once" function
// this means you can't access "result" outside of the function
var result;
return function(num){
// since this function is scoped inside "once", it has access to result
// set the result to itself (if aleady called), or the value returned from func
result = result || func(num);
// return the result
return result;
}
}
var onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
console.log(onceFunc(9001)); //should log 6