1

I'm using the following stub to protect against leaving console.log statements in a production application:

//  Protect against IE8 not having developer console open.
var console = console || {
    "log": function () {
    },
    "error": function () {
    },
    "trace": function () {
    }
};

This works fine in the sense that it prevents exceptions from being thrown when I call console.log in IE8 without the developer tools open. However, I dislike the fact that if I open dev. tools after the code has loaded -- I still don't see my log messages.

Is it possible to have both? My attempts have led me to infinite recursions of console.log calls. I also found this: http://log4javascript.org/ but I'd rather not unless entirely necessary

EDIT: To clarify: I simply want to not throw an exception if dev. console isn't open, but use the console if it is opened later.

4

2 回答 2

0

制作一个包装函数并调用它而不是console.log.

function log(msg) {
  var console = window.console;
  if (console && typeof console.log === 'function') {
    console.log(msg);
  }
}

这样,它就不会覆盖window.console并使其以后不可用。

于 2013-09-05T21:11:14.423 回答
0

是的,您可以执行以下操作:

if (typeof(console) === "undefined") {
   var console = { 
      log: function() { },
      error: function() { },
      trace: function() { }
   };
}
于 2013-09-05T20:56:18.820 回答