我想将console.log
方法克隆到函数中。我们称之为log
。
我试过了:
log = console.log;
log (1);
> TypeError: Illegal invocation
这只发生在客户端。我在NodeJS控制台上工作正常:
$ node
> log = console.log
[Function]
> log ("Hello World!")
Hello World!
undefined
第一个问题是:为什么它在服务器端工作正常但在客户端没有?
我想覆盖console.log
方法,但在将其保存到另一个变量之后。
oldLog = console.log;
console.log = function () {
/* do my stuff */
oldLog.apply(this, arguments);
}
我该如何解决?
答案 0 :(得分:5)
console.log
要求this
成为console
对象。
如果您将其称为独立功能,this
将为window
,因此无法正常工作。
Node.js将console.log
设置为console.log.bind(console)
,因此它始终有效
(见source)
如果您使用正确的this
(使用bind()
或call()
或apply()
)来调用它,它也可以在浏览器中使用。