我可以覆盖Javascript Function对象来记录所有函数调用吗? [英] Can I override the Javascript Function object to log all function calls?

查看:88
本文介绍了我可以覆盖Javascript Function对象来记录所有函数调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以覆盖Function对象的行为,这样我可以在每个函数调用之前注入行为,然后继续正常进行吗?具体来说,(虽然一般的想法本身很有趣)我可以在每个函数调用时登录到控制台而无需在任何地方插入console.log语句吗?然后正常行为继续?

Can I override the behavior of the Function object so that I can inject behavior prior t every function call, and then carry on as normal? Specifically, (though the general idea is intriguing in itself) can I log to the console every function call without having to insert console.log statements everywhere? And then the normal behavior goes on?

我确实认识到这可能会出现严重的性能问题;即使在我的开发环境中,我也无意进行此操作。但如果它工作,似乎是一个优雅的解决方案,以获得运行代码1000米的视图。我怀疑答案将向我展示更深入的javascript。

I do recognize that this will likely have significant performance problems; I have no intention of having this run typically, even in my development environment. But if it works it seems an elegant solution to get a 1000 meter view on the running code. And I suspect that the answer will show me something deeper about javascript.

推荐答案

显而易见的答案如下:

var origCall = Function.prototype.call;
Function.prototype.call = function (thisArg) {
    console.log("calling a function");

    var args = Array.prototype.slice.call(arguments, 1);
    origCall.apply(thisArg, args);
};

但这实际上会立即进入无限循环,因为调用的行为console.log 执行一个函数调用,它调用 console.log ,它执行一个函数调用,调用 console。 log ,... ...

But this actually immediately enters an infinite loop, because the very act of calling console.log executes a function call, which calls console.log, which executes a function call, which calls console.log, which...

指出,我不确定这是可能的。

Point being, I'm not sure this is possible.

这篇关于我可以覆盖Javascript Function对象来记录所有函数调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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