javascript - 关闭挑战: returning same output from first call (Javascript)

标签 javascript closures

我面临以下挑战描述:

“编写一个函数一次,接受回调作为输入并返回一个函数。当第一次调用返回的函数时,它应该调用回调并返回该输出。如果它被多次调用,而不是调用再次回调它只会返回第一次调用时的输出值”

给您的代码是:

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 oneFunc 充当 n。我是否需要将第一个返回的 6 或 n=4 保存到变量中?

最佳答案

可能有更好的解决方案,但这就是我想出的。我尝试在代码中添加注释来解释它在做什么,但如果您有任何其他问题,请告诉我: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

关于javascript - 关闭挑战: returning same output from first call (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847101/

相关文章:

javascript - 如何从父级访问 iframe 内的 DIV

javascript - setFindTimeout 和 pollUntil with Intern 用于在初始页面加载时不可见的元素

javascript - 为什么即使索引已关闭,该索引号似乎仍有效?

javascript - MobX 和 HMR : Please avoid replacing stores as the change might not propagate to all children

javascript - 如何在webAPP中的firebase中添加新条目

javascript - 如何在 bxslider 中的每张幻灯片之间应用不同的延迟

ios - Swift 1.2 - 由类函数的闭包参数引起的错误

swift - 如何将字符串转换为字符数组?

javascript - 这是闭包在 useState 钩子(Hook)中的工作方式吗?

ios - 在 swift 的嵌套闭包中正确放置捕获列表