我正在编写一个插件。为此,我会记录一些事情,比如警告,necc等等。要记录它们,我将使用控制台,但如果某些浏览器不支持控制台,则可能会出现错误。要处理这个错误,我想使用这个代码:检查控制台是否存在
if (typeof console == 'undefined') console = {};
if (typeof console.log == 'undefined') console.log = function() {};
if (typeof console.debug == 'undefined') console.debug = function() {};
if (typeof console.info == 'undefined') console.info = function() {};
if (typeof console.warn == 'undefined') console.warn = function() {};
if (typeof console.error == 'undefined') console.error = function() {};
这个工作是否正确或有更好的选择?
我相信你可以做'console.log(“whatever”)||真的;'或类似的东西。我在几个月前看到它,并且不记得开发者是如何做到的,但我认为这是正确的。 – Endophage 2011-05-17 20:18:59
@Endophage如果控制台不受支持,你会得到一个“无法调用方法”的未定义日志,一个正确的在线检查将是: 'console && console.log && console.log(“whatever”)' – Lior 2012-10-31 14:10:07