JavaScript - run once without booleans

后端 未结 9 1198
一个人的身影
一个人的身影 2021-01-30 17:42

Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?

Spe

9条回答
  •  旧时难觅i
    2021-01-30 17:58

    What about an immediately invoked anonymous function?

    (function () {
    
        // code in here to run once
    
    })();
    

    the code will execute immediately and leave no trace in the global namespace.

    If this code is going to need to be called from elsewhere, then a closure can be used to ensure that the contents of a function are run only once. Personally, I prefer this to a function that rewrites itself as I feel doing so can cause confusion, but to each their own :) This particular implementation takes advantage of the fact that 0 is a falsy value.

    var once = (function() {
      var hasRun = 0;  
      return function () {
        if (!hasRun) {
          hasRun++;   
    
          // body to run only once
    
          // log to the console for a test       
          console.log("only ran once");
        }              
      }
    })();
    
    // test that the body of the function executes only once
    for (var i = 0; i < 5; i++) 
      once();
    

提交回复
热议问题