how to detect a function was called with javascript

后端 未结 5 1996
隐瞒了意图╮
隐瞒了意图╮ 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:50

    Use decorator pattern.

    // your function definition
    function yourFunction() {}
    
    // decorator
    function callItOnce(fn) {
        var called = false;
        return function() {
            if (!called) {
                called = true;
                return fn();
            }
            return;
        }
    }
    
    yourFunction(); // it runs
    yourFunction(); // it runs    
    yourFunction = callItOnce(yourFunction);
    yourFunction(); // it runs
    yourFunction(); // null
    

    This solution provides a side-effect free way for achieving your goal. You don't have to modify your original function. It works nice even with library functions. You may assign a new name to the decorated function to preserve the original function.

    var myLibraryFunction = callItOnce(libraryFunction);
    myLibraryFunction(); // it runs
    myLibraryFunction(); // null
    libraryFunction(); // it runs
    

提交回复
热议问题