TypeError: console.log.apply的调用非法

132

如果你在Chrome控制台中运行以下代码:

console.log.apply(null, [array])

Chrome 给您返回了一个错误:

// TypeError: Illegal Invocation

为什么?(在OSX上通过Chrome 15进行测试)

1个回答

182

当执行上下文从控制台更改为任何其他对象时,它可能无法正常工作:

This is expected because console.info expects its "this" reference to be console, not window.

console.info("stuff")
stuff
undefined
console.info.call(this, "stuff")
TypeError: Illegal invocation
console.info.call(console, "stuff")
stuff
undefined

This behavior is expected.

https://bugs.chromium.org/p/chromium/issues/detail?id=48662


25
如果你需要将其作为一个函数使用,可以使用 console.info.bind(console)。 - C B
3
所有支持ES5的浏览器都可以使用console.info.call(console, "stuff") - mucaho
2
同样适用于apply方法:console.info.apply(console, arguments) - PeterM
同样的论点也适用于其他函数,例如console.log()和document.writeln()。因此,如果使用call()或apply(),请始终提供正确的执行上下文。或者,如@JohnWilliams所指出的那样,使用bind()。 - Alan C. S.
1
当开发者工具 F12 未打开时,这仍适用于 IE11/Edge。 - Benny Bottema

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接