【问题标题】:Function count calls函数计数调用
【发布时间】:2011-11-06 18:30:23
【问题描述】:

我是 JavaScript 初学者,所以请耐心等待 =)

我正在尝试编写一个函数来计算它被调用的次数。到目前为止,我所拥有的是一个带有显式递增计数器的函数:

var increment = function () {
    var i = 0;
    this.inc = function () {i += 1;};
    this.get = function () {return i;};
};

var ob = new increment();
ob.inc();
ob.inc();
alert(ob.get());

但我想知道如何只调用ob();,因此该函数可以自动增加对自身的调用。这可能吗?如果可以,怎么做?

【问题讨论】:

    标签: javascript function closures


    【解决方案1】:
    var increment = function() {
        var i = 0;
        return function() { return i += 1; };
    };
    
    var ob = increment();
    

    【讨论】:

    • +1。 @naveen:菜鸟似乎正朝着他/她自己的方向前进。 :)
    • @Shef:我说很好。在我意识到关闭之前有一段时间。但后来 js 是我的第二语言。一个带有警报框的小福利 :)
    • @naveen:我刚刚同意你的看法。 :) 我也很惊讶地看到 OP,自称是初学者,试图学习闭包。
    • OP 的代码与我第一次尝试学习 JS 的代码几乎相同。成为菜鸟 JS 程序员并不意味着成为菜鸟程序员。
    • @Vaibhav:增量函数本身不会增加任何内容。它返回一个函数。 ob 持有该功能。
    【解决方案2】:
    ob = function f(){  
      ++f.count || (f.count = 1);   // initialize or increment a counter in the function object
      return f.count; 
    }
    

    【讨论】:

      【解决方案3】:

      为任何函数包装一个计数器:

      /**
       * Wrap a counter to a function
       * Count how many times a function is called
       * @param {Function} fn Function to count
       * @param {Number} count Counter, default to 1
       */
      function addCounterToFn(fn, count = 1) {
        return function () {
          fn.apply(null, arguments);
          return count++;
        }
      }
      

      https://jsfiddle.net/n50eszwm/

      【讨论】:

        【解决方案4】:

        单线选项:

        const counter = ((count = 0) => () => count++)()
        

        使用示例:

        > counter()
        0
        > counter()
        1
        > counter()
        2
        > counter()
        3
        > counter()
        4
        > counter()
        5
        > counter()
        6
        

        【讨论】:

          【解决方案5】:

          还有新的 Generator functions,它提供了一种编写计数器的简单方法:

          function* makeRangeIterator(start = 0, end = 100, step = 1) {
            let iterationCount = 0;
            for (let i = start; i < end; i += step) {
              iterationCount++;
              yield i;
            }
            return iterationCount;
          }
          
          const counter = makeRangeIterator();
          const nextVal = () => counter.next().value;
          
          console.log("nextVal: ", nextVal()); // 0
          console.log("nextVal: ", nextVal()); // 1
          console.log("nextVal: ", nextVal()); // 2
          console.log("nextVal: ", nextVal()); // 3
          

          【讨论】:

            猜你喜欢
            • 2023-03-11
            • 2014-11-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-29
            • 2017-12-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多