Skip to main content
 首页 » 编程设计

javascript之在 JavaScript 中实现 'once' 函数

2025年01月19日10www_RR

我有来自 Jasmine.js 的这个规范,它测试了 once功能。我不确定如何实现这样的功能。

/* Functions that decorate other functions.  These functions return a version of the function 
   with some changed behavior. */ 
 
// Given a function, return a new function will only run once, no matter how many times it's called 
describe("once", function() { 
  it("should only increment num one time", function() { 
    var num = 0; 
    var increment = once(function() { 
      num++; 
    }); 
    increment(); 
    increment(); 
 
    expect(num).toEqual(1); 
  }); 
}); 

我不太明白我应该在这里做什么。我知道我应该创建一个函数一次(myFunction){},但除此之外,我被卡住了。我发现这与闭包有关,但我仍然无法理解。

请您参考如下方法:

从 UnderscoreJS 源复制:

  _.once = function(func) { 
    var ran = false, memo; 
    return function() { 
      if (ran) return memo; 
      ran = true; 
      memo = func.apply(this, arguments); 
      func = null; 
      return memo; 
    }; 
  }; 

http://underscorejs.org/docs/underscore.html