Reputation: 1
I'm working to take over a code base that tests to make sure console.warn
exists like this:
if (window.console) {
console.warn("shhaabang");
}
However, my problem with this is that it works only in the browser where you have a window object. This would seem to work too.
if (console && typeof console.warn == 'function') {
console.warn("shhaabang");
}
Are there any downsides to this method? Are there any better methods that don't assume the existence of window
? Should I just see if window or global exists first and check both?
CLARIFICATION It should be obvious at the least that I'm testing this in something that doesn't have the window
object. But, to be explicit I am running this in node.js as well as the browser
Upvotes: 5
Views: 2105
Reputation: 138
Consider using a javascript logging framework that has already handed this rather than reinventing the wheel. For instance, try loglevel.
Here's how loglevel handles safe logging (view full source):
function realMethod(methodName) {
if (typeof console === undefinedType) {
return false; // We can't build a real method without a console to log to
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}
Upvotes: 2
Reputation: 36
you shouldn't do
if(console && typeof console.warn == "function"){ ... }
becuase this throws an error if console is not defined
you can use this
e.g.:
if(this.console){
console.warn("shhaabang");
}
EDIT: oh sorry, i just noticed 2 things:
1) this does only work if this
hasn't been changed... thanks @Evan Carroll
2) this does not work in strict mode
, because in strict mode
, this
is undefined
so here's another approach:
var c;
try {
c = console;
} catch(e){
// console is not defined
}
if(c) {
// console is defined
}else{
// this will not throw because you declared `c` earlier
}
Upvotes: 0