29

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?

0

2 Answers 2

83

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:.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for explaining why, not just how.
This will not working < IE9, because console.log is a Host object, not an instance of Function. Therefore, console.log does not have a "bind" method. This will cause headache.
Incidentally, with ES6/ES7, you'll be able to do ::console.log to have a log bound to console.
16

The simple way will be to wrap it in a function:

var log = function (l) {
   console.log(l);
}

But make note that console.log can take an unlimited number of arguments so the appropriate way will be do this:

var l = function () {
   console.log.apply(console, arguments);
}

3 Comments

This is the preferred solution.
@TaylorMac Why ?
let log = (...l) => console.log(...l); in es6 to keep multiple variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.