When I edit production code (little fixes) I want to add console.log
for example, but not to break page for users who don't have firebug or don't use chrome I decide to redefine console object:
if (console == undefined) {
console = {
log : function(){},
info : function(){},
warn : function(){},
error : function(){开发者_JAVA技巧}
};
};
After I inserted this code, JS-execution was broken in browsers that don't have console object (IE, firefox without firebug, etc). (By "broken" I mean that code after these lines doesn't execute at all) Why did it happen?
(console == undefined)
will throw a ReferenceError
if console is undefined.
Use typeof
instead which does not throw ReferenceErrors
for undeclared variables
(typeof console === "undefined")
Try this:
if ( window.console === undefined ) {
window.console = {
// Your methods
}
}
It's not really good to compare a variable to undefined
, since undefined
is a simple undefined variable.
You can use something like this:
if (!window.console)
console = {
log : function(){},
info : function(){},
warn : function(){},
error : function(){}
};
Edit: I just found this: How do I print debug messages in the Google Chrome JavaScript Console?
If console is not defined in the js then it will throw an error instead use typeof to check the variable's existense
if (typeof console == 'undefined') { }
If you change your if(console == undefined)
to if(window.console == undefined)
everything will work
Any of the answer above should work fine.
One note: You might also add "dir" to your list of empty methods, since people sometimes use console.dir()
to print out objects.
精彩评论