Adding console.log to every function automatically

Here’s a way to augment all functions in the global namespace with the function of your choice:

function augment(withFn) {
    var name, fn;
    for (name in window) {
        fn = window[name];
        if (typeof fn === 'function') {
            window[name] = (function(name, fn) {
                var args = arguments;
                return function() {
                    withFn.apply(this, args);
                    return fn.apply(this, arguments);

                }
            })(name, fn);
        }
    }
}

augment(function(name, fn) {
    console.log("calling " + name);
});

One down side is that no functions created after calling augment will have the additional behavior.

Leave a Comment