JavaScript - run once without booleans

后端 未结 9 1192
一个人的身影
一个人的身影 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条回答
  •  臣服心动
    2021-01-30 17:54

    (function (){
    
      var run = (function (){
    
        var func, blank = function () {};
    
        func = function () {
          func = blank;
    
          // following code executes only once 
          console.log('run once !');
        };
    
        return function(){
          func.call();
        };
      })();
    
      run();
      run();
      run();
      run();
    
    })();
    

提交回复
热议问题