2017-09-13 183 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>

取一個變量並增加點擊次數並進行操作。