Javascript 如何仅在第一次调用函数时执行if语句?
我在函数中有一个if语句。如何仅在第一次调用函数时执行if语句?您可以使用此Javascript 如何仅在第一次调用函数时执行if语句?,javascript,if-statement,Javascript,If Statement,我在函数中有一个if语句。如何仅在第一次调用函数时执行if语句?您可以使用此 var notFirstRun = false; function myFunction(){ if (notFirstRun) return; // this will "exit" the function else notFirstRun = true; if (foo == bar){ // your if statement // somecode }
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
}
})();
使用布尔标志设置您已经使用了该函数ad if true跳过该函数更好地将该布尔值存储为函数的属性,如
myFunction.hasBeenCalled=true
@JanDvorak,因为这样做是有意义的。不会用函数细节污染应用程序的其余部分。保持对函数执行,谢谢!