How to determine if a function has been called without setting global variable

后端 未结 6 986
别跟我提以往
别跟我提以往 2020-12-29 05:09

I am looking for a good technique to get away from what I am tempted to do: to set a global variable.

The first time someone runs a function by clicking a button it

6条回答
  •  -上瘾入骨i
    2020-12-29 05:25

    While @Levi's answer ought to work just fine, I would like to present another option. You would over write the init function to do nothing once it has been called.

    var init = function () {
       // do the initializing
    
        init = function() {
            return false;
        }
    };
    

    The function when called the first time will do the init. It will then immediately overwrite itself to return false the next time its called. The second time the function is called, the function body will only contain return false.

    For more reading: http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/

提交回复
热议问题