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

后端 未结 6 991
别跟我提以往
别跟我提以往 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:38

    The correct approach is to use the Javascript Proxy APIs to trap the function calls using apply handler.

    const initFun = (args) => {
      console.log('args', args);
    }
    const init = new Proxy(initFun, {
      apply(target, thisArg, args){
        target.calls = target.calls ? target.calls + 1 : 1;
        return target.apply(thisArg, args);
      }
    });
    
    init('hi');
    console.log(init.calls); // 1
    init('hello');
    console.log(init.calls); // 2

提交回复
热议问题