Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何仅在第一次调用函数时执行if语句?_Javascript_If Statement - Fatal编程技术网

Javascript 如何仅在第一次调用函数时执行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 }

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

使用布尔标志设置您已经使用了该函数ad if true跳过该函数更好地将该布尔值存储为函数的属性,如
myFunction.hasBeenCalled=true
@JanDvorak,因为这样做是有意义的。不会用函数细节污染应用程序的其余部分。保持对函数执行,谢谢!