我有一个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/
当您致电时console.log
,该功能log
将console
作为this
值接收.
log
直接调用时,this
值将undefined
处于严格模式,或者全局对象处于非严格模式.
要解决它,您可以使用bind
绑定console
作为this
值log
:
var log = console.log.bind(console);
Run Code Online (Sandbox Code Playgroud)