Assigning console.log to another object (Safari issue)

Posted by Trevor Burnham on Stack Overflow See other posts from Stack Overflow or by Trevor Burnham
Published on 2010-04-11T23:51:55Z Indexed on 2010/04/12 0:03 UTC
Read the original article Hit count: 300

Filed under:
|
|
|

I wanted to keep my logging statements as short as possible while preventing console from being accessed when it doesn't exist; I came up with the following solution:

var _ = {};
if (console) {
    _.log = console.debug;
} else {
    _.log = function() { }
}

To me, this seems quite elegant, and it works great in Firefox 3.6 (including preserving the line numbers that make console.debug more useful than console.log). But it doesn't work in Safari 4. (Haven't tested in other browsers yet.) If I follow the above with

console.debug('A')
_.log('B');

the first statement works fine in both browsers, but the second generates a "TypeError: Type Error" in Safari. Is this just a difference between how Firebug and the Safari Web Developer Tools implement console? If so, it is VERY annoying on Apple's part. (I get the same results in both browsers if I bind the console function to a prototype and then instantiate, rather than binding it directly to the object.)

I could, of course, just call console.debug from an anonymous function assigned to _.log, but then I'd lose my line numbers. Any other ideas?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about console