检查控制台是present [英] Check whether console is present

查看:109
本文介绍了检查控制台是present的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个插件。为此,我将记录了一些东西,说警告,NECC的事情,等要记录他们,我会用控制台,但可以有,如果一些浏​​览器不支持控制台错误。为了处理这个错误,我想用这个code的:

I am writing a plugin. For that I will log a few things, say warnings, necc things, etc. To log them I will use console, but there can be an error if some browser doesn't support console. To handle this error, I am thinking of using this code:

    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() {};

将这项工作正确或是否有更好的选择?

Will this work right or is there a better option?

推荐答案

您正在接近它的权利。然而,你能缩短它一下:

You're approaching it right. You could however shorten it a bit:

if(typeof console === "undefined") {
    console = {
        log: function() { },
        debug: function() { },
        ...
    };
}

这使您可以使用的console.log / console.debug等没有先检查是否控制台对象被定义。我建议始终包括这个片段中,如果你正在登录,因为它很容易忘记删除,它会破坏你的网站如果没有控制台是present。

This allows you to use console.log/console.debug etc without first checking if a console object is defined. I recommend to always include this snippet if you are logging since it is easy to forget to remove and it will break your site if no console is present.

这篇关于检查控制台是present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆