2013-09-28 46 views

回答

3

您可以使用此

var notFirstRun = false; 
function myFunction(){ 
    if (notFirstRun) return; // this will "exit" the function 
    else notFirstRun = true; 

    if (foo == bar){ // your if statement 
     // somecode 
    } 
    // rest of the function 
} 

或事件的詳細作用域:

var myFunction = (function(notFirstRun) { 
    return function() { 
     if (notFirstRun) return; // this will "exit" the function 
     else notFirstRun = true; 

     if (foo == bar) { // your if statement 
      // somecode 
     } 
     // rest of the function 
    } 
})(); 
+2

更好的商店,布爾作爲函數的屬性像'myFunction.hasBeenCalled = true' – Prinzhorn

+1

@prinzhorn原因? –

+0

@JanDvorak,因爲這樣做是有道理的。 – Prinzhorn