谁能告诉我为什么这不起作用?
Array.prototype.forEach.call(document.body.children, console.log);
我收到以下错误:
Uncaught TypeError: Illegal invocation(…)(anonymous function)
这似乎是无稽之谈,因为以下两者都有效:
Array.prototype.forEach.call(document.body.children, function () {console.log(arguments)});
Array.prototype.forEach.call(document.body.children, l=>console.log(l));
NOTE: the function being called (
console.log
in this case) is just an example, the original intent was to usedocument.body.removeChild
instead, but this failed in the same way.ANOTHER NOTE: I've only tried this in Chrome. I tried the following in a node.js console and it worked fine:
Array.prototype.forEach.call(myArray, console.log)
最佳答案
这是因为必须在 console
对象上调用 console.log
方法:
var log = console.log;
log(123); /* TypeError: 'log' called on an object that
does not implement interface Console. */
log.call(console, 123); /* Works */
您可以通过将第三个参数传递给 forEach
来修复,该参数确定 this
值:
Array.prototype.forEach.call(document.body.children, console.log, console);
或者您可以将 console.log
绑定(bind)到 console
:
Array.prototype.forEach.call(document.body.children, console.log.bind(console));
还有一个bind operator的提案:
Array.prototype.forEach.call(document.body.children, ::console.log);
关于javascript - Array.prototype.forEach.call 给出 TypeError : Illegal invocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416462/