Suppose I want to include some calls in console.log for some legitimate production reason, say for something like a unit test harness. Obviously, I would not want this to raise a premature exception if there is no console in the browser or if not.
What is the best way to create a simple log function to write stuff to the console or without crashing without errors if the console is missing?
The accepted answer to the question related above:
var log = Function.prototype.bind.call(console.log, console); log.apply(console, ["this", "is", "a", "test"]);
Could this log function be called normally in IE, and using apply here just to show it? And from a related question, I assume that this will not succeed if the IE console is closed when it starts, so log will not work even after opening the console, right? If this is not the case, can someone explain how this works?
This ycombinator article seems relevant. Are they talking about the same IE behavior as the question related above?
Function.prototype.apply.apply(console.log, [console, arguments]);
It works both on IE9, broken console.log, and on a regular .log console from other providers. The same hack as using Array.prototype.slice to convert arguments to a real array.
This works well on my Chrome console.
function echo(){ Function.prototype.apply.apply(console.log, [console, arguments]); }
Simplified:
function echo(){ Function.apply.call(console.log, console, arguments); }
Add a check and a refund:
function echo(){ return window.console && console.log && Function.apply.call(console.log, console, arguments); }
The above example seems adequate to me. However, I do not have IE on hand to test it. Is this a smart approach for secure console.log packaging?
Other questions
Following the link below in the navigation, we see the code:
Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments));
What is the purpose of converting arguments to an array in this case? I think in some browser this will not work if you do not? And, unlike opera behavior and hassle-free browsers, shouldn't something like this pretty much work for any other browser? And prototype serves the purpose in the examples above, or we're just pedantic ... Function.call.call or Object.call.call or, if it is important, isNaN.call.call seems to work just as well as Function.prototype.call.call .