zoukankan      html  css  js  c++  java
  • 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) {}
    }
    

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

  • 相关阅读:
    爬取豆瓣分页照片下载
    css布局:三列布局,中间内容优先加载
    解决在IE下label中IMG图片无法选中radio的几个方法
    CSS架构:最新最佳实践
    JavaScript登陆弹窗,可拖拽
    网站变成灰色的代码
    5个jQuery的备选轻量级移动客户端开发(Mobile development)类库
    jQuery 底部漂浮导航当前位置突出 + 锚点平滑滚动
    Exchange 2007 自定义传输规则
    基于jQuery打造TabPanel
  • 原文地址:https://www.cnblogs.com/smart-girl/p/11045141.html
Copyright © 2011-2022 走看看