Javascript 如果未定义,则 js 覆盖 console.log
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3767924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
js override console.log if not defined
提问by Radu Maris
Which solution do you recommend, 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 later in the code
if(debug) {
console.log(something);
}
Second:override console.log
第二:覆盖console.log
try {
console.log
} catch(e) {
if (e) {
console.log = function() {}
}
};
// And all you need to do in the code is
console.log(something);
回答by Andy E
Neither, but a variation of the second. Lose the try...catch
and check for existence of the console object properly:
两者都不是,而是第二种的变体。丢失try...catch
并正确检查控制台对象是否存在:
if (typeof console == "undefined") {
window.console = {
log: function () {}
};
}
console.log("whatever");
回答by Jameson Quinn
Or, in coffeescript:
或者,在咖啡脚本中:
window.console ?=
log:-> #patch so console.log() never causes error even in IE.
回答by Frankie
EDIT:Andy's answeris way more elegant than the quick hack I've posted below.
编辑:安迪的回答比我在下面发布的快速黑客更优雅。
I generally use this approach...
我一般用这种方法...
// prevent console errors on browsers without firebug
if (!window.console) {
window.console = {};
window.console.log = function(){};
}
回答by Suresh
I've faced a similar bug in my past, and I overcame it with the code below:
我过去遇到过类似的错误,我用下面的代码克服了它:
if(!window.console) {
var console = {
log : function(){},
warn : function(){},
error : function(){},
time : function(){},
timeEnd : function(){}
}
}
回答by David
I came across this post, which is similar to the other answers:
我遇到了这篇文章,与其他答案类似:
http://jennyandlih.com/resolved-logging-firebug-console-breaks-ie
http://jennyandlih.com/resolved-logging-firebug-console-breaks-ie
回答by Mike Kormendy
The following will achieve what you are looking for:
以下将实现您正在寻找的内容:
window.console && console.log('foo');
回答by Sean
window.console = window.console || {};
window.console.log = window.console.log || function() {};