简体   繁体   English

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

[英]How to best safely use console.log and console.warn?

I'm working to take over a code base that tests to make sure console.warn exists like this: 我正在努力接管一个代码库,测试以确保console.warn存在如下:

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

However, my problem with this is that it works only in the browser where you have a window object. 但是,我的问题是它只能在你有窗口对象的浏览器中工作。 This would seem to work too. 这似乎也有效。

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

Are there any downsides to this method? 这种方法有什么缺点吗? Are there any better methods that don't assume the existence of window ? 有没有更好的方法不承担window的存在? Should I just see if window or global exists first and check both? 我应该先看看窗口或全局是否存在并检查两者?

CLARIFICATION It should be obvious at the least that I'm testing this in something that doesn't have the window object. 澄清至少我应该明白,我在没有window对象的东西中测试它。 But, to be explicit I am running this in node.js as well as the browser 但是,要明确我在node.js以及浏览器中运行它

Consider using a javascript logging framework that has already handed this rather than reinventing the wheel. 考虑使用已经交付了这个而不是重新发明轮子的javascript日志框架。 For instance, try loglevel . 例如,尝试loglevel

Here's how loglevel handles safe logging ( view full source ): 以下是loglevel如何处理安全日志记录( 查看完整源代码 ):

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]);
            };
        }
    }
}

you shouldn't do 你不应该这样做

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

becuase this throws an error if console is not defined 因为如果未定义控制台,则会抛出错误

you can use this 你可以用this

eg: 例如:

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

EDIT: oh sorry, i just noticed 2 things: 1) this does only work if this hasn't been changed... thanks @Evan Carroll 2) this does not work in strict mode , because in strict mode , this is undefined 编辑:噢,对不起,我只注意到两两件事:1)如果这确实只是工作this还没有改变...感谢@Evan卡罗尔2)本不工作strict mode ,因为在strict modethisundefined

so here's another approach: 所以这是另一种方法:

var c;
try {
  c = console;
} catch(e){ 
  // console is not defined
}

if(c) {
  // console is defined
}else{
  // this will not throw because you declared `c` earlier
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM