Possible Duplicate:
alias to chrome console.log
This is really silly, but I can’t abbreviate console.log (I’m using Chrome). Here’s my naive attempt:
var log = console.log;
log("Bingo"); // Uncaught TypeError: Illegal invocation
Should I be using apply()? But then I’d have to pass along the arguments, right?
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.logto a variable, and have the call apply toconsole, is to use thebindmethod on thelogmethod, passingconsoleas the argument:There is a hidden
thisargument to every method, and because of arguably bad language design, it’s not closured when you get a reference to a method. Thebindmethod’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 tobindshould always be thethisargument, but you can actually assign any number of arguments using it.Using
bindhas the notable advantage that you don’t lose the method’s ability to accept more arguments. For instance,console.logcan actually accept an arbitrary number of arguments, and they will all be concatenated on a single log line.Here is an example of using
bindto preassign more arguments toconsole.log:Invoking
debugLogwill prefix the log message withDEBUG:.