Is console.log a regular object? [duplicate]
-
14-07-2021 - |
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?
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:
Function.prototype.call
Function.prototype.apply
(not used here, but still of interest)Function.prototype.bind
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow