如果未定义,js 会覆盖 console.log [英] js override console.log if not defined

查看:28
本文介绍了如果未定义,js 会覆盖 console.log的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您推荐哪种解决方案,第二种更简单(代码更少),但使用它有缺点?

Which solution do you recommend, the second is simpler ( less code ), but there are drawbacks on using it ?

首先:(设置全局调试标志)

// 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

Second: override 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);

推荐答案

不是,而是第二种的变体.丢失 try...catch 并正确检查控制台对象是否存在:

Neither, but a variation of the second. Lose the try...catch and check for existence of the console object properly:

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

console.log("whatever");

这篇关于如果未定义,js 会覆盖 console.log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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