I've previously used the following based on other SO answers (without really understanding the need for (nor the workings of) the prototype.apply.apply
var mylogger = {
    log: function () {
        if (window.console) {
            if (window.console.log) {
                Function.prototype.apply.apply(console.log, [console, arguments]);
            }
        }
    },
    ...
};
while this prevents IE from crapping on itself, it also make the line number reporting unusable (it always reports the apply.apply.. line.
I was playing around a little and discovered that the following seems to do exactly what I need, i.e. prevent IE from crapping on itself and report the line number where mylogger.log(..) was called from..
var mylogger = {
    // function invocation returning a safe logging function..
    log: (function () {
        if (window.console && window.console.log && Function.prototype.bind) {
            return window.console.log.bind(window.console);
        } else {
            return function () {};
        }
    }()),
    ...
};
I've done some basic testing on IE/FF/Chrome without seeing any issues.. is this reasonable or is there a better way?
What you're doing is fine I guess, but if you aren't adding any additional functionality, you could do something simple and in one line:
window.console = (window.console || {debug:function(){},log:function(){},error:function(){}});
You could, of course, add other console functions if you use them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With