How to get Javascript Function Calls/Trace at Runtime

前端 未结 8 1932
天命终不由人
天命终不由人 2020-12-23 13:56

As I interact with my AJAX based application at RUNTIME I\'d like the console to spit out all the functions it\'s calling. (so no stack trace, or breakpoints, or pr

8条回答
  •  情深已故
    2020-12-23 14:43

    A variation on Briguy37's solution, I wrote one that accepts a function to call before each method. It also works with ECMAScript 6 classes, where methods are not enumerated by for...in. I'm using it to modify Object prototypes, to add logging to all new instances of my object.

    function inject(obj, beforeFn) {
        for (let propName of Object.getOwnPropertyNames(obj)) {
            let prop = obj[propName];
            if (Object.prototype.toString.call(prop) === '[object Function]') {
                obj[propName] = (function(fnName) {
                    return function() {
                        beforeFn.call(this, fnName, arguments);
                        return prop.apply(this, arguments);
                    }
                })(propName);
            }
        }
    }
    
    function logFnCall(name, args) {
        let s = name + '(';
        for (let i = 0; i < args.length; i++) {
            if (i > 0)
                s += ', ';
            s += String(args[i]);
        }
        s += ')';
        console.log(s);
    }
    
    inject(Foo.prototype, logFnCall);
    

提交回复
热议问题