Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  162] [ 4]  / answers: 1 / hits: 15679  / 12 Years ago, fri, march 9, 2012, 12:00:00

This is just out of curiosity, but do any of you have an idea why this code won't work?



[1, 2, 3, 4, 5].forEach(console.log);

// Prints 'Uncaught TypeError: Illegal invocation' in Chrome


On the other hand, this seems to work fine:



[1, 2, 3, 4, 5].forEach(function(n) { console.log(n) });


So... ?


More From » arrays

 Answers
45

Actually as @SLaks pointed out, console.log seems to be using this internally and when it's passed as a parameter this now refers to the array instance.



The workaround for that is simply:



var c = console.log.bind(console);
[1,2,3,4,5].forEach(c);


[#86949] Thursday, March 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paolam

Total Points: 437
Total Questions: 107
Total Answers: 106

Location: Aland Islands
Member since Wed, Nov 17, 2021
3 Years ago
;