Skip to content

Instantly share code, notes, and snippets.

@renemonroy
Forked from bgrins/Log-.md
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save renemonroy/d63e332ec620e408add3 to your computer and use it in GitHub Desktop.

Select an option

Save renemonroy/d63e332ec620e408add3 to your computer and use it in GitHub Desktop.
// Prevent errors on console methods when no console present and expose a global 'log' function.
(function () {
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
if (Function.prototype.bind) {
window.log = Function.prototype.bind.call(console.log, console);
}
else {
window.log = function() {
(typeof console.log === 'object' ? log.apply.call(console.log, console, arguments) : console.log.apply(console, arguments));
}
}
})();
function Test() {}
Test.prototype.extraMethod = function() { }
var expressions = [
["A single string"],
[123],
[["An", "Array", "Of", "Strings"]],
[{ an: "obj", withNested: { objects: { inside: "of", it: true }}}],
[Test],
[new Test()]
];
function logAllWithWrapper() {
for (var i = 0; i < expressions.length; i++) {
log.apply(log, expressions[i]);
}
}
function logAllWithNative() {
for (var i = 0; i < expressions.length; i++) {
Function.prototype.apply.call(console.log, console, expressions[i]);
}
}
log("\n-----------");
log("Logging all expressions with wrapper log function");
log("-----------\n");
logAllWithWrapper();
log("\n-----------");
log("Logging all expressions with native console.log function");
log("-----------\n");
logAllWithNative();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment