Node vs Chrome, assigning console.log to a variabl

2019-02-17 00:00发布

问题:

When I assign console.log to a variable in node.js it works fine,

var l = console.log
l(1) # outputs 1

However, if I do the same thing in Chromium 30's dev tools,

var l = console.log
l(1) # TypeError: Illegal invocation

How come it doesn't work in Chromium's dev tools? Why am I getting,

TypeError: Illegal invocation

回答1:

Exactly why this requirement is in place, I don't know, but I guess Chrome's console.log requires the value of this to be console. If you want to store it in a variable, you'll have to bind the value of this:

var l = console.log.bind(console);


回答2:

Node.js console does console.log = console.log.bind(this) in constructor.