views:

72

answers:

2

Witch solution do you recomend, the second is simpler ( less code ), but there are drawbacks on using it ?
first: (set a global debug flag)

// the first line of code
var debug = true;
try
{
    console.log
}catch(e)
{
    if(e){
        debug=false;
    }
};
// then latter in the code
if(debug)
{
    console.log(something);
}

second: override console.log

try
{
    console.log
}catch(e)
{
    if(e)
    {
        console.log = function() {}
    }
};
// and all you need tot do in the code is
console.log(something);

Thank you

+4  A: 

Neither, but a variation of the second. Lose the try...catch and check for existence of the console object properly:

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

console.log("whatever");
Andy E
Presumably you either want to do `this.console = ...` or `var console = ...`? As you have it at the moment, you'd get an error in ECMAScript 5 strict mode.
Tim Down
@Tim: thanks, it was an oversight. I think `window.console` would be best for portability.
Andy E
Portability in the sense of being able to move this code into a function, rather than portability between environments?
Tim Down
@Tim: yes, er, well a function that may run in a different context. I think I need more coffee this morning :-)
Andy E
+2  A: 

I generally use this approach...

// prevent console errors on browsers without firebug
if (!window.console) {
    window.console = {};
    window.console.log = function(){};
}
Frankie