Array.prototype.forEach.call 给出 TypeError: 非法调用

Array.prototype.forEach.call gives TypeError: Illegal invocation

本文关键字:非法 调用 TypeError 给出 prototype forEach call Array      更新时间:2023-09-26

谁能告诉我为什么这不起作用?

Array.prototype.forEach.call(document.body.children, console.log);

我收到以下错误:

未捕获的类型错误:非法调用(...((匿名功能(

这似乎是无稽之谈,因为以下两者都有效:

Array.prototype.forEach.call(document.body.children, function () {console.log(arguments)});
Array.prototype.forEach.call(document.body.children, l=>console.log(l));

注意:被调用的函数(在本例中console.log(只是一个示例,最初的目的是改用document.body.removeChild,但这以同样的方式失败了。

另一个注意事项:我只在Chrome中尝试过这个。我在节点.js控制台中尝试了以下内容,它工作正常:

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绑定到console

Array.prototype.forEach.call(document.body.children, console.log.bind(console));

还有一个绑定运算符的建议:

Array.prototype.forEach.call(document.body.children, ::console.log);