0

I'm wondering why does the following code gives an Illegal Invocation error

_.flow( console.log ) ( 123 ) // Illegal Invocation

function log(){ _.each(arguments, function(o) { console.log(o) }); }
_.flow( log ) ( 123 ) // 123

Running this on Chrome Version 49.0.2623.112 (64-bit) with lodash v4.13.1

To be sepcific I ran this on the developer tools on Chrome by pressing Ctr+Shift+J on lodash's documentation page

jkris
  • 5,851
  • 1
  • 22
  • 30

1 Answers1

0

Updated answer, based on feedback.

console.log must be called properly -- in other words, it must have the right this value when called. Calling it as a method of console is one way, but bind can also be used.

Example code (taken from my browser's console)

// Give us a test function
function ctest(console) { console("It worked") }
ctest(console.log); // This fails

// Set up a properly bound reference
var clog = console.log.bind(console);
ctest(clog); // This works.

Old Snippet removed

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
  • Thank's I updated the question. I'm surprised that your snippet is working. Which makes me more intrigued. – jkris Jun 14 '16 at 06:27
  • ok I found something while digging around, which accroding to it your snippet should NOT work but clearly it is... what's your secret! http://stackoverflow.com/questions/8159233/typeerror-illegal-invocation-on-console-log-apply – jkris Jun 14 '16 at 06:29
  • I'll bet the difference is -- `console.log` is being over-ridden by the snippet environment and it isn't calling the real browser one. Hmm..didn't think of that. I"ll have to test/explore later on. – Jeremy J Starcher Jun 14 '16 at 12:58
  • @jkris Updated my answer for you. – Jeremy J Starcher Jun 14 '16 at 13:49