How to safely wrap `console.log`? How to safely wrap `console.log`? javascript javascript

How to safely wrap `console.log`?


The problem with wrappers is that they will obfuscate file name and line number of the source of the log message.

Simple IE7 and below shim that preserves Line Numbering for other browsers:

/* console shim*/(function () {    var f = function () {};    if (!window.console) {        window.console = {            log:f, info:f, warn:f, debug:f, error:f        };    }}());


Sorry, there was a bug in my post. Don't know how I missed it.

The PROPER way to create a global console object, if it does not exist:

if (typeof console === "undefined"){    console={};    console.log = function(){        return;    }}


Can this log function be called normally on IE, and the use of apply here is just to show it's possible?

Yes, and yes. That particular example was aimed squarely at the "is it a real function" part of the linked question.

And, I assume from the linked question that this will fail if IE's console is closed when it runs, so log won't work even after the console opens, correct?

Correct. As explained in my answer on that question, the console object is not exposed until the first time the developer tools are opened for a particular tab. Most developers use a console shim, in which case the Function#bind approach becomes a little obsolete because you may as well use the Function#apply.apply method.

What is the purpose of converting arguments to an array in this case?

There isn't one, it's redundant. Unless it's a custom log implementation, in which case the developer may have a reason to convert an arguments object to an array.

And does prototype serve a purpose in the above examples, or are we just being pedantic...

Well, yes and no. Some developer may have unwittingly changed Function.call to a custom function or value. Of course, they could break Function.prototype.call too, but this is far less likely to happen by accident.