JavaScript - run once without booleans

后端 未结 9 1195
一个人的身影
一个人的身影 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 18:06

    I like Lekensteyn's implementation, but you could also just have one variable to store what functions have run. The code below should run "runOnce", and "runAgain" both one time. It's still booleans, but it sounds like you just don't want lots of variables.

    var runFunctions = {};
    
    function runOnce() {
      if(!hasRun(arguments.callee)) {
       /* do stuff here */
       console.log("once");
      }
    }
    
    function runAgain() {
      if(!hasRun(arguments.callee)) {
       /* do stuff here */
       console.log("again");
      }
    }
    
    
    function hasRun(functionName) {
     functionName = functionName.toString();
     functionName = functionName.substr('function '.length);
     functionName = functionName.substr(0, functionName.indexOf('('));
    
     if(runFunctions[functionName]) {
       return true;
     } else {
       runFunctions[functionName] = true;
       return false;
     }
    }
    
    runOnce();
    runAgain();
    runAgain();
    

提交回复
热议问题