0

Once upon a time I ad an assignment task on one of interviews that hasn't been giving me to sleep since:

Need to log a arguments-object in console in one line with a date in the end. As objects(to be able to inspect those), not string( Array prototype.join() - is not a solution in this case)

a fail attempt(out of function scope):

var fn = function () {
  var arr = Array.prototype.slice.call(arguments);
  arr.push(new Date().toJSON());
  Function.prototype.call.apply( console.log, arr );  
}

fn( 1, 'a', [2, 3], {a:1} );

logs:

Uncaught TypeError: Illegal invocation 

Any ideas?

Nik Terentyev
  • 2,270
  • 3
  • 16
  • 23

1 Answers1

0

Use this for logging

Function.prototype.call.apply( console.log.bind(console), arr );

instead of

Function.prototype.call.apply( console.log, arr ); 

It will do the work.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • I'm not sure, but what I know... **The console's log function expects this to refer to the console (internally). when passed as callback.** [see here](http://stackoverflow.com/questions/8904782/uncaught-typeerror-illegal-invocation-in-javascript) – Mritunjay Oct 13 '14 at 02:21
  • 1
    This is incorrect. You're losing the first argument because it tries to be bound as the `this` value of the `log` method via `.call()`, but you've already bound `this`, so it gets ignored. –  Oct 13 '14 at 02:21