JavaScript - run once without booleans

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

    I just ran into this problem, and ended up doing something like the following:

    function runOnce () {
        if (!this.alreadyRan) {
            // put all your functionality here
            console.log('running my function!');
    
            // set a property on the function itself to prevent it being run again
            this.alreadyRan = true;
        }
    }
    

    This takes advantage of the fact that Javascript properties are undefined by default.

提交回复
热议问题