how to detect a function was called with javascript

后端 未结 5 2003
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 08:18

I have a javascript function.

How to check:

  • if function was called ( in section have this function), then not

5条回答
  •  执念已碎
    2020-12-05 08:48

    Static variables

    Here's how to create static (like in C) variables using self calling functions to store your static variables in a closure.

    var myFun = (function() {
      var called = false;
      return function() {
        if (!called) {
          console.log("I've been called");
          called = true;
        }
      }
    })()
    

    Abstract the idea

    Here's a function that returns a function that only gets called once, this way we don't have to worry about adding boiler plate code to every function.

    function makeSingleCallFun(fun) {
      var called = false;
      return function() {
        if (!called) {
          called = true;
          return fun.apply(this, arguments);
        }
      }
    }
    
    var myFun = makeSingleCallFun(function() {
      console.log("I've been called");
    });
    
    myFun(); // logs I've been called
    myFun(); // Does nothing

提交回复
热议问题