克隆console.log函数

时间:2014-03-30 14:47:08

标签: javascript node.js

我想将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);
 }

我该如何解决?

1 个答案:

答案 0 :(得分:5)

console.log要求this成为console对象。

如果您将其称为独立功能,this将为window,因此无法正常工作。

Node.js将console.log设置为console.log.bind(console),因此它始终有效 (见source

如果您使用正确的this(使用bind()call()apply())来调用它,它也可以在浏览器中使用。