我记得总是当我想将 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/