Question

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?

Was it helpful?

Solution

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top