log = console.log,引发非法调用错误 [英] log = console.log, throws illegal invocation error
本文介绍了log = console.log,引发非法调用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个javascript文件,该文件为 console.log
的缩写,例如,
I have a javascript file, that makes a shorthand for console.log
as,
var log = console.log
log("this message is logged with shortened keyword")
在运行时,它将引发错误,
On running, it throws error as,
Uncaught TypeError: Illegal invocation
Jsfiddle ---- https://jsfiddle.net/w42vp7zg/
Jsfiddle ---- https://jsfiddle.net/w42vp7zg/
推荐答案
调用控制台时。 log
,函数 log
将收到 console
作为 this
值。
When you call console.log
, the function log
will receive console
as the this
value.
直接调用 log
时,在严格模式下,此
值为未定义
;在非严格模式下,此全局对象为全局对象。
When you call log
directly, the this
value will be undefined
in strict mode or the global object in non-strict mode.
要解决此问题,可以使用 绑定
将控制台
绑定为 log
this 值>:
To solve it, you can use bind
to bind console
as the this
value of log
:
var log = console.log.bind(console);
这篇关于log = console.log,引发非法调用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文