只运行一次函数 - 函数式编程JavaScript

时间:2014-05-28 14:48:09

标签: javascript

我的代码如下,

var a = 0;
var addByOne = doOnce(function() { a += 1; });

// I need to define a doOnce function here


// Run addByOne two times
addByOne();
addByOne();

这将导致变量a保持2作为其值。我的问题是,我如何制作doOnce函数,以便它会导致在doOnce中运行函数(在上面的情况下,函数(){a + = 1;})只有一次。因此,无论调用addByOne多少次,变量a都只会增加一次。

由于

2 个答案:

答案 0 :(得分:3)

这可以通过创建一个doOnce函数来实现,该函数返回一个包装器,用于调用已传递的函数(如果尚未运行)。这可能看起来像这样;

doOnce = function(fn) {
    var hasRun = false,
        result;
    return function() {
        if (hasRun === false) {
            result = fn.apply(this, arguments);
            hasRun = true;
        }
        return result;
    }
}

答案 1 :(得分:0)

试试这个:

function doOnce(fn) {
  // Keep track of whether the function has already been called
  var hasBeenCalled = false;
  // Returns a new function
  return function() {
    // If it has already been called, no need to call it again
    // Return (undefined)
    if (hasBeenCalled) return;
    // Set hasBeenCalled to true
    hasBeenCalled = true;
    return fn.apply(this, arguments);
  }
}

如果需要,您可以跟踪返回值并返回而不是未定义。