在 JavaScript 中覆盖 console.log

uni*_*oot 2 javascript overriding console.log

我想覆盖console.log方法以在调用时调用一组任务console.log。我提到了其他 Stackoverflow 答案,但这给了我错误:

未捕获的 RangeError:超出最大调用堆栈大小。

这就是我想要做的:

backupconsolelog = console.log;

console.log = function(arguments)
{
    //do my tasks;

    backupconsolelog(arguments);
}
Run Code Online (Sandbox Code Playgroud)

更新 1:不知何故成功地覆盖了 console.log,但我现在无法console.log(displaySomethingInConsole)在覆盖完成的同一个 .js 文件中执行。这以某种方式导致递归调用console.log,并再次给出Uncaught RangeError: Maximum call stack size exceeded.

如何在同一个 .js 文件中使用 console.log()?

更新 2:我有一个check()由 overrided 调用的函数console.log。但是,函数console.log内部有一个调用check()导致Maximum call stack size exceeded.错误。

更新 3:再次出错!:(

未捕获的类型错误:非法调用

var _log = window.console.log;
window.console.log = function () {
_log.apply(this, arguments);
check();
};

_log("aaa");
check() {};
Run Code Online (Sandbox Code Playgroud)

更新 4绑定 console_log,即console.log.bind(console)清除它。

And*_*lad 5

如果您收到最大调用堆栈大小超出错误,则几乎肯定意味着您的函数正在无限递归地调用自身。您找到的解决方案以及RaraituL展示的解决方案应该可以完美运行。您可能不止一次调用设置调用重定向的代码部分。

// First time:
backupconsolelog = console.log.bind(console);
console.log = function() {
    backupconsolelog.apply(this, arguments);
    /* Do other stuff */
}
// console.log is now redirected correctly

// Second time:
backupconsolelog = console.log;
// Congratulations, you now have infinite recursion
Run Code Online (Sandbox Code Playgroud)

您可以添加一些调试信息console.log显然不使用,debugger;而是尝试创建一个自动断点),您可以在其中设置重定向以查看调用代码的位置和时间。

更新

这可能属于评论: 您的console.log重定向函数check显然调用了一些名为 的函数。这个check函数然后调用console.log,如果你的函数 - 不是原始函数。让check函数调用原始实现。

backupconsolelog = console.log.bind(console);

console.log = function() {
    check();
    backupconsolelog.apply(this, arguments);
}

function check() {
    // This will call your function above, so don't do it!
    console.log('Foo');

    // Instead call the browser's original implementation:
    backupconsolelog('Foo');
}
Run Code Online (Sandbox Code Playgroud)

更新 2

浏览器实现的内部工作console.log可能取决于也可能不取决于console被设置为this参考。因此,您应该存储console.log bound to console,就像在我的代码中一样。