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

今天看到项目中引入了一个插件,我超级惊讶
1037363-20190618144907912-1617305246.png
为什么引入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,直接打开控制台就可以调试。
后来又和同事聊了下:
1037363-20190618145211019-862317012.png
同事说:“这个是解决低版本IE的调试,不过也没啥用 IE调试和定位不是那么容易的,未来几年后这个就不需要了,IE 微软都快要抛弃了”
看了下作者里面的源码,比如看了下package.json了解了下作者写这个插件涉及到的npm包
1037363-20190619003022109-926545366.png
根据这个我大概得出的结论就是使用一些工具,将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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值