我正在尝试为 console.log
编写一个包装器。
我在函数原型(prototype)中找到了 .apply
函数,但它给了我错误:
function _log() {
if (opts.debug) console.log.apply(this, arguments);
}
opts.debug
是我的配置数组中的一个键。
错误:
Uncaught TypeError: Illegal invocation at :2:13 at Object.InjectedScript._evaluateOn (:905:140) at Object.InjectedScript._evaluateAndWrap (:838:34) at Object.InjectedScript.evaluate (:694:21)
我尝试这样做的方式有什么问题吗?并且,怎样做才是正确的呢?谢谢。
最佳答案
console.log
期望作为 console
的方法调用,即使用 console
作为接收者(this
参数,apply
的第一个参数)。目前,您正在将 this
传递给 apply
,无论 this 是什么(可能是全局对象),它都不是 console
对象。使用
function _log() {
if (opts.debug) console.log.apply(console, arguments);
// ^^^^^^^
}
关于javascript - console.log 的包装器 - 非法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31817754/