js类封装

将js方法封装成类,好处就是团队开发中避免命名冲突,部分类整理代码如下:


function LocalStorageHelper() {
    //检测浏览器是否支持localStorage
    this.checkIsSupportLS = function () {
        return !window.localStorage || true;
    }
    //根据key获得单个localStorage的值
    this.getSingleLS = function (key) {
        if (!this.checkIsSupportLS()) { return; }
        return window.localStorage.getItem(key);
    }
    //获取localStorage所有的键值对(返回json对象)
    this.getAllLS = function () {
        if (!this.checkIsSupportLS()) { return; }
        var storage = window.localStorage,
            list = [];
        for (var i = 0; i < storage.length; i++) {
            list[i] = { 'key': storage.key(i), 'value': this.getSingleLS(storage.key(i)) };
        }
        return list;
    }
    //创建单个localStorage键值对
    this.createSingleLS = function (key, value) {
        if (!this.checkIsSupportLS()) { return; }
        var storage = window.localStorage;
        if (storage.getItem(key)) { this.removeSingleLS(key); }
        storage.setItem(key, value);
    }
    //创建多个localStorage键值对(json对象,格式:[{'key':'','value':''},{'key':'','value':''}])
    this.createListLS = function (list) {
        if (!this.checkIsSupportLS() || !list) { return; }
        var storage = window.localStorage;
        for (var i = 0; i < list.length; i++) {
            this.createSingleLS(list[i].key, list[i].value);
        }
    }
    //移除单个localStorage键值对
    this.removeSingleLS = function (key) {
        if (!this.checkIsSupportLS()) { return; }
        window.localStorage.removeItem(key);
    }
    //移除所有localStorage键值对
    this.removeAllLS = function () {
        if (!this.checkIsSupportLS()) { return; }
        window.localStorage.clear();
    }
}

function CommMethods() {

    //类似于C#的string.Format()
    this.format = function (str, args) {
        var result = str;
        if (args.length)
            for (var i = 0; i < args.length; i++) {
                if (typeof (args[i]) != undefined) {
                    var reg = new RegExp('({[' + i + ']})', 'g');
                    result = result.replace(reg, args[i]);
                }
            }
        return result;
    }

    //console.log('aaa','type:[log,info,warn,error]':default:log)
    this.log = function (msg, type) {
        //var _log = console.log;
        //console.log = function () {//模糊化输出内容
        //    _log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:transparent;text-shadow:0 0 2px rgba(0,0,0,.5);');
        //};
        var now = new Date(),
            y = now.getFullYear(),
            m = now.getMonth() + 1,//!js中月份是从0开始的
            d = now.getDate(),
            h = now.getHours(),
            min = now.getMinutes(),
            s = now.getSeconds(),
            time = this.format('{0}/{1}/{2} {3}:{4}:{5}', [y, m, d, h, min, s]),
            outMsg = this.format('{0}> {1}', [time, msg ? msg : '']);
        switch (type) {
            case 'log':
                console.log(outMsg);
                break;
            case 'info':
                console.info(outMsg)
                break;
            case 'warn':
                console.warn(outMsg);
                break;
            case 'error':
                console.error(outMsg);
                break;
            default:
                console.log(outMsg);
                break;
        }
    }

    //检测是否为正数
    this.isPositiveNumber = function (a) {
        var reg = /^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
        return reg.test(a);
    }

    //检测是否为数字--(数字包含小数)--
    this.isNumber = function (a) {
        return !isNaN(a);
    }

    //检测是否为整数
    this.isInt = function (a) {
        var reg = /^(-|\+)?\d+$/;
        return reg.test(a);;
    }

    //检测是否为有效的长日期格式 - "YYYY-MM-DD HH:MM:SS" || "YYYY/MM/DD HH:MM:SS"
    this.isDateTime = function (str) {
        var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
        if (result == null) return false;
        var d = new Date(result[1], result[3] - 1, result[4], result[5], result[6], result[7]);
        return (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4] && d.getHours() == result[5] && d.getMinutes() == result[6] && d.getSeconds() == result[7]);
    }

    //检测是否为 YYYY-MM-DD || YYYY/MM/DD 的日期格式
    this.isDate = function (str) {
        var result = str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
        if (result == null) return false;
        var d = new Date(result[1], result[3] - 1, result[4]);
        return (d.getFullYear() == result[1] && d.getMonth() + 1 == result[3] && d.getDate() == result[4]);
    }

    //检测是否为有效的电子邮件
    this.isEmail = function (str) {
        var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
        return reg.test(str);
    }

    //去除字符串的首尾的空格
    this.trim = function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }

    //返回字符串的实际长度, 一个汉字算2个长度
    this.strRealLength = function (str) {
        return str.replace(/[^\x00-\xff]/g, "**").length;
    }

    //检测是否为中国邮政编码(6位)
    this.isPostCode = function (str) {
        var reg = /[1-9]\d{5}(?!\d)/;
        return reg.test(str);
    }

    //检测是否为国内座机电话号码(0511-4405222 或 021-87888822)
    this.isTellPhone = function (str) {
        var reg = /\d{3}-\d{8}|\d{4}-\d{7}/;
        return reg.test(str);
    }

    //检测是否为腾讯QQ号
    this.isQQ = function (str) {
        var reg = /\d{15}|\d{18}/;
        return reg.test(str);
    }

    //检测是否为身份证(15位或18位)
    this.isIDCard = function (str) {
        var len = this.strRealLength(str),
            reg15 = /\d{15}|\d{18}/,
            reg18 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
        if (len === 15) {
            return reg15.test(str);
        }
        else if (len === 18) {
            return reg18.test(str);
        }
        else { return false; }
    }

    //检测文本是否为空
    this.checkIsNull = function (a) {
        return (a == '' || a == null || typeof (a) == undefined);
    }

    //XML转成JSON
    this.xmlToJson = function (xml) {
        // Create the return object
        var obj = {};
        if (xml.nodeType == 1) { // element
            // do attributes
            if (xml.attributes.length > 0) {
                obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
                }
            }
        } else if (xml.nodeType == 3) { // text
            obj = xml.nodeValue;
        }
        // do children
        if (xml.hasChildNodes()) {
            for (var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof (obj[nodeName]) == "undefined") {
                    obj[nodeName] = xmlToJson(item);
                } else {
                    if (typeof (obj[nodeName].length) == "undefined") {
                        var old = obj[nodeName];
                        obj[nodeName] = [];
                        obj[nodeName].push(old);
                    }
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
        return obj;
    }

    //去除数组重复项
    this.removeListRepeat = function (list) {
        var $ = list,
            o1 = {},
            o2 = {},
            o3 = [],
            o;

        for (var i = 0; o = $[i]; i++) {
            if (o in o1) {
                if (!(o in o2)) o2[o] = o;
                delete $[i];
            } else {
                o1[o] = o;
            }
        }

        $.length = 0;

        for (o in o1) {
            $.push(o);
        }

        for (o in o2) {
            o3.push(o);
        }

        return o3;

    }

}

function CookieHelper() {
    // 1. 设置COOKIE 

    // 简单型 
    this.setCookieSimple = function (c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
    }

    // 完整型 
    this.setCookieBoth = function (name, value, expires, path, domain, secure) {
        var expDays = expires * 24 * 60 * 60 * 1000,
            expDate = new Date();
        expDate.setTime(expDate.getTime() + expDays);
        var expString = ((expires == null) ? '' : (';expires=' + expDate.toGMTString())),
            pathString = ((path == null) ? '' : (";path=" + path)),
            domainString = ((domain == null) ? '' : (';domain=' + domain)),
            secureString = ((secure == true) ? ';secure' : '');
        document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString;
    }

    // 2.获取指定名称的cookie值: 
    this.getCookie = function (c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + '=')
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1
                c_end = document.cookie.indexOf(';', c_start)
                if (c_end == -1) c_end = document.cookie.length
                return unescape(document.cookie.substring(c_start, c_end))
            }
        }
        return ''
    }

    // 3.删除指定名称的cookie: 
    this.removeCookie = function (name) {
        var expDate = new Date();
        expDate.setTime(expDate.getTime() - 100);
        document.cookie = name + '=;expires=' + expDate.toGMTString();
    }

    // 4. 检测cookie: 
    this.checkIsSupportCookie = function () {
        var result = false;
        if (navigator.cookiesEnabled) {return true; }
        document.cookie = 'testcookie=yes;';
        var setCookie = document.cookie;
        if (setCookie.indexOf('testcookie=yes') > -1) {
            result = true;
        } else {
            document.cookie = '';
        }
        return result;
    }    

}

$(function () {
    var localstoragehelper = new LocalStorageHelper();
    var commmethod = new CommMethods();
    localstoragehelper.checkIsSupportLS();
    commmethod.checkIsNull();
});


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值