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

后端 未结 6 988
别跟我提以往
别跟我提以往 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条回答
  •  悲&欢浪女
    2020-12-29 05:38

    What you could do is unhook the init function from the prototype.

    ​var Obj = function () {
        this.init = function () {
            document.write("init called
    "); this.init = null; } } var o = new Obj(); if (o.init) document.write("exists!
    "); o.init(); if (o.init) document.write("exists!
    "); o.init();

    ​ The first if will be true and print exists! but since the function removes itself, the second if will fail. In my example, I call the second init unconditionally just to show that nothing will happen, but of course you could call it only if it exists:

    if (o.init) o.init();
    

    http://jsfiddle.net/coreyog/Wd3Q2/

提交回复
热议问题