js override console.log if not defined
你推荐哪种解决方案,第二种更简单(代码更少),但使用它有缺点吗?
第一:(设置全局调试标志)
1 2 3 4 5 6 7 8 9 10 11 12 13 | // 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); } |
第二:覆盖console.log
1 2 3 4 5 6 7 8 9 | try { console.log } catch(e) { if (e) { console.log = function() {} } }; // And all you need to do in the code is console.log(something); |
两者都不是,而是第二种的变种。 丢失
1 2 3 4 5 6 7 | if (typeof console =="undefined") { window.console = { log: function () {} }; } console.log("whatever"); |
或者,在coffeescript中:
1 2 | window.console ?= log:-> #patch so console.log() never causes error even in IE. |
编辑:安迪的答案比我在下面发布的快速黑客更优雅。
我一般都用这种方法......
1 2 3 4 5 | // prevent console errors on browsers without firebug if (!window.console) { window.console = {}; window.console.log = function(){}; } |
我在过去遇到过类似的错误,我用下面的代码克服了它:
1 2 3 4 5 6 7 8 9 | if(!window.console) { var console = { log : function(){}, warn : function(){}, error : function(){}, time : function(){}, timeEnd : function(){} } } |
1 2 | window.console = window.console || {}; window.console.log = window.console.log || function() {}; |
以下将实现您的目标:
1 | window.console && console.log('foo'); |
我遇到过这篇文章,与其他答案类似:
http://jennyandlih.com/resolved-logging-firebug-console-breaks-ie