如何在计算函数调用次数时调用函数内的闭包

时间:2017-09-13 13:53:55

标签: javascript

我想计算点击时调用函数的次数。到目前为止,我有这个,但它不是很有效。任何人都可以帮忙吗?

function test(){
    var count = (function({
        var i = 0;
        return function(){
           return i += 1;
        }
     })();

   if(count() == 2){
     // do this
   }

}

像这样调用函数:

<select onclick="javascript: test();">

看起来计数功能没有被正确调用。如何调用该函数并对其执行操作?我希望在一定数量的点击次数下执行逻辑。

3 个答案:

答案 0 :(得分:3)

var count = 0;
function test(){
   count++;
   if(count == 2){
     // do this
     console.log('do something');
   }
}
<label onclick="javascript: test();">Test</label>

获取变量并增加点击次数并执行操作。

答案 1 :(得分:1)

你可以用一个闭包来包裹这个电话。

function countUsage(methodToWrap, methodContext) {
  const
    wrapContext = methodContext || this;
  let
    count = 0;
  
  // Return a method, this is the wrapped call.
  return function methodWrapper() {
    // Increase the counter by 1.
    count++;
    // Call the original method with the arguments.
    methodToWrap.apply(wrapContext, arguments);
    // Log the number of times the method was called.
    console.log(`The method has been called ${count} times`); 
  }
}

function methodToWrap(text) {
  console.log(`Log line ${text}`);
}

function sumToWrap(a, b) {
  console.log(`Sum of ${a} + ${b} = ${a+b}`);
}

const
  wrappedLog = countUsage(methodToWrap),
  wrappedSum = countUsage(sumToWrap);

// For these three calls you will see the count is increased with each call.
wrappedLog('hello');
wrappedLog('how');
wrappedLog('are you');

// This will result in a log line that there has been 1 call as it is a different method.
wrappedSum(3, 4);

答案 2 :(得分:-2)

这对你有用吗?

&#13;
&#13;
Paragraph itemLine9 = new Paragraph(@"*" + whBarCode + "*", bc39);
p.Add(itemLine9);
&#13;
    var i = 0;
    function test(){
        var count = (function() {
            return function(){
               return i += 1;
            }
         })();
       if(count() == 2){
         console.log('reached goal')
         // do this
       }
    
      alert('current count' +i)
    
    }
&#13;
&#13;
&#13;

关于你的项目:

<select onclick="test()"><option>select</option></select>

您通常在错误的地方使用括号等,并始终将值设置为0.

相关问题