Node vs Chrome, assigning console.log to a variable?

随声附和 提交于 2019-12-04 00:51:59

问题


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.



来源:https://stackoverflow.com/questions/19887424/node-vs-chrome-assigning-console-log-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!