如何仅在第一次调用函数时执行 if 语句

How to perform if statement only at first call of function?

本文关键字:执行 if 语句 函数 调用 何仅 第一次      更新时间:2023-09-26

我在函数中有一个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
    }
    // 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
    }
})();