You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS实现类似lodash _.once的单次执行函数报undefined错如何解决?

_.once 实现问题修复方案

现有代码错误点

  • Function.call传参错误:func.call(arguments)的第一个参数应为函数执行的this上下文,后续才是入参,现有写法既错误修改了目标函数的this指向,也没有正确传递调用参数,导致执行异常。
  • 参数收集时机错误:现有逻辑在调用_.once()时就收集参数,但实际使用中参数是在调用返回的包装函数(如示例中的oneTimeFunction('hello'))时才传入,完全拿不到实际业务参数。
  • 示例目标函数无返回值:你给出的示例函数function(string) { string.split(''); }没有return语句,就算执行逻辑正确也会返回undefined,如果需要返回反转后的字符串,需要补全返回逻辑。
  • 重复调用返回不符合预期:现有逻辑重复调用返回null,不符合_.once返回首次执行结果的要求。

修复后代码

_.once = function (func) {
  let called = false;
  let cachedResult = null;
  // 入参类型校验
  if (typeof func !== 'function') {
    throw new TypeError('入参需要是函数类型');
  }

  return function (...callArgs) {
    if (!called) {
      called = true;
      // 正确传递this上下文和调用时传入的参数
      cachedResult = func.apply(this, callArgs);
    }
    // 所有调用都返回第一次的执行结果
    return cachedResult;
  }; 
};

测试用例

const oneTimeFunction = _.once(function(string) { 
  // 补全返回逻辑,实现字符串反转
  return string.split('').reverse().join(''); 
})

// 第一次调用,正常执行返回结果
console.log(oneTimeFunction('hello')) // 输出:olleh
// 第二次及后续调用,直接返回缓存的第一次结果,不会重新执行原函数
console.log(oneTimeFunction('test')) // 输出:olleh

内容的提问来源于stack exchange,提问作者reallygoodatcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 04:12:02