javascript - console.log() 在控制台以外的对象上调用

标签 javascript this console.log function-binding

我记得总是当我想将 console.log 作为回调参数传递给某个函数时,它不起作用,除非我使用 bind() 方法将 console 绑定(bind)到它。

例如:

const callWithTest = callback => callback('test');
callWithTest(console.log); // That didn't use to work.
callWithTest(console.log.bind(console)); // That worked (and works) fine.

参见 Uncaught TypeError: Illegal invocation in javascript .

但是,最近我注意到 console.log() 即使在控制台以外的对象上调用时也能正常工作。例如:

console.log.call(null, 'test');

记录 'test'

它何时以及为何发生变化?规范对此有任何说明吗?

最佳答案

Editor's Draft of Console API曾经说过:

Logging APIs SHOULD all be callable functions allowing them to be passed as arguments to error handling callbacks, forEach methods, etc.

这不再包含在 the current version of the specification 中.

我以为 Chrome 和 Node.js 将其更改为像规范中那样工作,但它似乎甚至在它之前就这样工作了。

我还是很好奇它是什么时候变的,是什么原因。

关于javascript - console.log() 在控制台以外的对象上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39499845/

相关文章:

javascript - *在*构造函数中声明的属性在实例中可见。为什么?

javascript - 如何在控制台中以表格格式显示多维Javascript数组?

javascript - 获取子元素的值(value)

f# - F# 中的自标识符是否有标准命名约定?

javascript - 如何强制处理正确处理运动的负值?

javascript - 只要属性 attr ('title' )的值发生变化,span.label 的 html 就会自动更改

javascript - 无法解构属性,因为它是未定义的

javascript - 在 Meteor 中使用 Jquery $(this)

javascript - 显示当前对象值控制台日志

javascript - mootools:从 HTML 创建新的 DOM 元素