This fails because references to Javascript methods do not include a reference to the object itself. A simple and correct way to assign the method console.log
to a variable, and have the call apply to console
, is to use the bind
method on the log
method, passing console
as the argument:
var log = console.log.bind(console);
There is a hidden this
argument to every method, and because of arguably bad language design, it's not closured when you get a reference to a method. The bind
method's purpose is to preassign arguments to functions, and return a function that accepts the rest of the arguments the function was expecting. The first argument to bind
should always be the this
argument, but you can actually assign any number of arguments using it.
Using bind
has the notable advantage that you don't lose the method's ability to accept more arguments. For instance, console.log
can actually accept an arbitrary number of arguments, and they will all be concatenated on a single log line.
Here is an example of using bind
to preassign more arguments to console.log
:
var debugLog = console.log.bind(console, "DEBUG:");
Invoking debugLog
will prefix the log message with DEBUG:
.