gpt4 book ai didi

javascript - 如何最安全地使用 console.log 和 console.warn?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:15:10 25 4
gpt4 key购买 nike

我正在努力接管测试代码库以确保 console.warn 像这样存在:

if (window.console) {                                                                                                                                                                                                                                                      
console.warn("shhaabang");
}

但是,我的问题是它只能在具有窗口对象的浏览器中工作。这似乎也行得通。

if (console && typeof console.warn == 'function') {                                                                                                                                                                                                                                                      
console.warn("shhaabang");
}

这种方法有什么缺点吗?有没有更好的方法不假设 window 的存在?我是否应该首先查看 window 或 global 是否存在,然后检查两者?

澄清 至少应该很明显,我在没有window 对象的对象中对此进行测试。但是,明确地说我在 node.js 和浏览器中运行它

最佳答案

考虑使用已经解决了这个问题的 javascript 日志记录框架,而不是重新发明轮子。例如,尝试 loglevel .

这是日志级别如何处理安全日志记录 ( view full source ):

function realMethod(methodName) {
if (typeof console === undefinedType) {
return false; // We can't build a real method without a console to log to
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}

function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}

关于javascript - 如何最安全地使用 console.log 和 console.warn?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com