Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is console.log a regular object? [duplicate]

Possible Duplicate:
If Javascript has first-class functions, why doesn’t this work?

In Chrome, the following produces Uncaught TypeError: Illegal invocation:

g = console.log;
g(1);

Why does this happen, and why can't I treat console.log like a regular object?

like image 545
pseudosudo Avatar asked Feb 18 '23 16:02

pseudosudo


1 Answers

It happens because you've lost the reference to console. You're just calling log directly, with no context. You can call the function in the context of console to make it work:

g.call(console, 1);

Or, to save you from doing that every time, you can bind the function back to the console object:

var g = console.log.bind(console);

References:

  • Function.prototype.call
  • Function.prototype.apply (not used here, but still of interest)
  • Function.prototype.bind
like image 116
James Allardice Avatar answered Feb 26 '23 23:02

James Allardice