2016-02-15 4 views
0

Может ли кто-нибудь сказать мне, почему это не работает?Array.prototype.forEach.call дает TypeError: Незаконный вызов

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 use document.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)

+1

'console.log.bind (консоль),' document.body.removeChild.bind (document.body) ' –

+0

Ах так что мне нужно, чтобы связать' документ. body' (или элемент DOM) Я вызываю 'removeChild' on - спасибо @SergeSeredenko – Robin

ответ

4

Это потому, что метод console.log должен быть вызван на console объекте:

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)); 

Th ERE также предложение о bind operator:

Array.prototype.forEach.call(document.body.children, ::console.log); 
Смежные вопросы