如果未定义,js 会覆盖 console.log

2022-01-11 00:00:00 console javascript firebug

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

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");

相关文章