console.js还有浏览器不支持?

今天看到项目中引入了一个插件,我超级惊讶

为什么引入console.js啊?
这个是插件的源码:https://github.com/yanhaijing/console.js
我搜到源作者对这个插件的描述:“console.js is a small javascript library, fix console is undefined”
啥?还能够没有console.log?console.log还能够是undefined?
我真的超级惊讶,我以为所有的浏览器都有console.log,直接打开控制台就可以调试。
后来又和同事聊了下:

同事说:“这个是解决低版本IE的调试,不过也没啥用 IE调试和定位不是那么容易的,未来几年后这个就不需要了,IE 微软都快要抛弃了”
看了下作者里面的源码,比如看了下package.json了解了下作者写这个插件涉及到的npm包

根据这个我大概得出的结论就是使用一些工具,将es6写法的js转成2015版本的,让浏览器识别,并且内部也会有断言。
看一下index.js中的内容

const apply = Function.prototype.apply;

export function polyfill() {
//判断window类型,有就是一个对象类型 为g
    const g = typeof window !== 'undefined' ? window : {};
    //g有个属性是console
    const _console = g.console || {};

    const methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'exception', 'error', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
    
    const console = {};
//便利console这个对象的方法
    for (let i = 0; i < methods.length; i++) {
        const key = methods[i];
        console[key] = function() {
                //判断console的方法是否存在
            if (typeof _console[key] === 'undefined') {
                return;
            }
            // 添加容错处理
            try {
                return apply.call(_console[key], _console, arguments);
            } catch (e) {}
        };
    }

    g.console = console;
}

export function safeExec(cmd, ...args) {
    try {
        return apply.call(console[cmd], console, args);
    } catch (e) {}
}
export function log(...args) {
    return safeExec('log', ...args);
}

export function info(...args) {
    return safeExec('info', ...args);
}

export function warn(...args) {
    return safeExec('warn', ...args);
}

export function error(...args) {
    return safeExec('error', ...args);
}

export function log1(msg) {
    try {
        return console.log('log:', msg);
    } catch(e) {}
}

export function warn1(msg) {
    try {
        return console.warn('warn:', msg);
    } catch(e) {}
}

export function error1(msg) {
    try {
        return console.error('error:', msg);
    } catch(e) {}
}

后记:其实我没有看懂,也不知道作者是怎么写这个的,我觉得很厉害。

原文地址:https://www.cnblogs.com/smart-girl/p/11045141.html