首页 > 解决方案 > 使另一个函数在 JS 中只能执行一次的函数

问题描述

我一直在努力创建一个函数,给定另一个函数将使第二个函数只能调用一次。与_.once()功能不同。

期望的结果如下:

const oneTimeFunction = _.once(function(string) { string.split(''); })

oneTimeFunction('hello')

//returns: 'olleh', and if called again it would have no effect returning the same thing a the original call.

目前这就是我所拥有的:

_.once = function (func) {
  var called = 0;
  let args = null;

  if (arguments.length > 1) {
    args = Array.prototype.slice.call(arguments,1);
  }

  return function () {
    if (called === 0) {
      console.log('being called');
      called ++;

      if (!args) {
        console.log('without apply');
        return func.call(arguments);
      } else {
        console.log('with apply');
        return func.apply(this,args);
      }
    } else {
      console.log('this has been called');
      return null;
    }
  }; 
};

我正在碰壁,因为即使我尝试了所有方法,它也会返回未定义的错误类型。任何帮助,即使是到达它可以调用函数的地方,而不管一次性的规定?谢谢!

标签: javascript

解决方案


在阅读您的问题时,我看到您希望始终在后续调用中返回第一个值:

“如果再次调用,返回与原始调用相同的内容将无效。”

所以我相信你想做这样的事情:

function computeOnce(myFn) {
  let origVal = undefined;

  return function (...args) {
    // if this is not set, this is the first call
    if (!origVal) {
      // execute the function and store it's return value
      origVal = myFn(...args);
    }
    return origVal;
  }
}

推荐阅读