2017-09-13 187 views
0

我想计算单击时调用函数的次数。我有这个目前为止,但它不工作。有人能帮忙吗?如何在调用函数调用次数时调用函数中的闭包

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

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

} 

调用函数,就像这样:

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

它看起来像count函数没有正确调用。我如何调用该函数并对其执行操作?我想在某些点击次数下执行逻辑。

+2

你似乎很大地过度复杂 - 为什么不把'count'变量放在'test'函数之外,并在被调用时增加它呢? –

回答

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);

+0

我很确定这是一种复杂的方式,因为OP希望和未使用他们的语言版本(ES5 vs ES6 +) – PeterS

+0

如果他只有一种方法,我们想保持计数,那么是的,这可能也是复杂。但是,如果他有多种方法需要跟踪他们的使用情况,这是一个很好的可重用模式。至于ES6,你可以将所有'const'和'let'替换为'var',它仍然可以工作。 – Thijs

-2

这是否对你的工作?

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) 
 
    
 
    }
<select onclick="test()"><option>select</option></select>

并在您的项目只是:

onlick="test()" 

你通常不得不在错误的地点等支架和pH值总是设置为0

+0

对于否定的人,你应该始终说明一个理由。没有人会通过否定来学习。或者编辑帖子或建议改进。 – PeterS

3

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

取一个变量并增加点击次数并进行操作。