log = console.log,抛出非法调用错误

2 javascript browser

我有一个javascript文件,这是一个简写为console.log,

var log = console.log
log("this message is logged with shortened keyword")
Run Code Online (Sandbox Code Playgroud)

在运行时,它会抛出错误,

Uncaught TypeError: Illegal invocation
Run Code Online (Sandbox Code Playgroud)

Jsfiddle ---- https://jsfiddle.net/w42vp7zg/

Ori*_*iol 7

当您致电时console.log,该功能logconsole作为this值接收.

log直接调用时,this值将undefined处于严格模式,或者全局对象处于非严格模式.

要解决它,您可以使用bind绑定console作为thislog:

var log = console.log.bind(console);
Run Code Online (Sandbox Code Playgroud)