2016-02-15 2 views
0

Quelqu'un peut-il me dire pourquoi cela ne fonctionne pas?Array.prototype.forEach.call donne TypeError: invocation illégale

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

je reçois l'erreur suivante:

Uncaught TypeError: Illegal invocation(…)(anonymous function)

Ce qui semble un non-sens que ce qui suit à la fois le travail:

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 (console)', 'document.body.removeChild.bind (document.body)' –

+0

Ah si je dois lier le document '. body' (ou l'élément DOM) J'appelle 'removeChild' sur - merci @SergeSeredenko – Robin

Répondre

4

C'est parce que la méthode console.log doit être appelée sur l'objet console:

var log = console.log; 
log(123); /* TypeError: 'log' called on an object that 
      does not implement interface Console. */ 
log.call(console, 123); /* Works */ 

Vous pouvez corriger en passant un troisième argument à forEach, qui détermine la valeur this:

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

Ou vous pouvez lier console.log à console:

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

Th avant est également une proposition de bind operator:

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