Skip to content

Instantly share code, notes, and snippets.

@nuintun
Last active June 6, 2016 08:47
Show Gist options
  • Save nuintun/9756388 to your computer and use it in GitHub Desktop.
Save nuintun/9756388 to your computer and use it in GitHub Desktop.
浏览器console兼容
浏览器console兼容

方法一:

// make it safe to use console.log always
(function (b){
  function c(){}

  for (var d = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","), a; a = d.pop();) {
    b[a] = b[a] || c;
  }
})((function (){
  try {
    console.log();
    
    return window.console;
  } catch (err) {
    return window.console = {};
  }
})());

方法二:

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || []; // store logs to an array for reference
  log.history.push(arguments);
  
  if (this.console) {
    arguments.callee = arguments.callee.caller;
    
    var newarr = [].slice.call(arguments);
    
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

方法三:

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  
  if(this.console){
    console.log(Array.prototype.slice.call(arguments));
  }
};

方法四:

// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
window.log = function (){
  return window.console && console.log && Function.prototype.apply.apply(console.log, [console, arguments]);
}

方法五:

// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
window.log = function (){
  return window.console && console.log && Function.apply.call(console.log, console, arguments);
}

参考:
介绍博客
console.log-wrapper
How to safely wrap `console.log`?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment