自动将 console.log 添加到每个函数 [英] Adding console.log to every function automatically

查看:24
本文介绍了自动将 console.log 添加到每个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过在某处注册全局钩子(即不修改实际函数本身)或通过其他方式调用任何函数时输出 console.log 语句?

Is there a way to make any function output a console.log statement when it's called by registering a global hook somewhere (that is, without modifying the actual function itself) or via some other means?

推荐答案

这是一种使用您选择的函数来扩充全局命名空间中的所有函数的方法:

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);
});

一个缺点是在调用 augment 之后创建的函数不会有额外的行为.

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

这篇关于自动将 console.log 添加到每个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆