【问题标题】:log = console.log, throws illegal invocation error [duplicate]log = console.log,抛出非法调用错误[重复]
【发布时间】:2015-08-07 15:51:33
【问题描述】:

我有一个 javascript 文件,它是 console.log 的简写,

var log = console.log
log("this message is logged with shortened keyword")

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

Uncaught TypeError: Illegal invocation

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

【问题讨论】:

  • 在 Firefox 上,错误可能更具描述性:TypeError: 'log' called on an object that does not implement interface Console.

标签: javascript browser


【解决方案1】:

当您调用console.log 时,函数log 将接收console 作为this 值。

当您直接调用log 时,this 的值将是严格模式下的undefined 或非严格模式下的全局对象。

要解决这个问题,可以使用bindconsole绑定为logthis值:

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

【讨论】:

  • 在理论上学习了applybind 函数多年后,终于找到了一个实际的用例……谢谢大佬
猜你喜欢
  • 2017-04-10
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
相关资源
最近更新 更多