小菜鸟与老司机的区别:

  我昨天呢,把cookie的封装方法,以及思路都说了,但是今天看了别个大神的代码才发现真的是小菜啊,先上代码——

  以下是我的:

(function (win,doc) {
    var GD16 = {
        /**
         * 创建cookie
         * @param argument json || string || null
         */
        Crecookie: function (argument) {
            var date = new Date();
            var d = new Date(date.setTime(date.getTime()+10000));


            if(argument){  //参数有值
                console.log(argument)
                if (typeof argument == 'object') {//创建
                    for (var i in argument) {
                        doc.cookie=i+'='+argument[i]+';expires='+ d.toGMTString();
                        console.log(i+'='+argument[i]+';expires='+ d.toGMTString())
                    }
                }
                else if (typeof argument == 'string') {//获取
                    doc.cookie=argument+'="";expires='+ new Date().toGMTString();
                }
                else {
                    return console.error('参数只能是json|string');
                }
            }else{  // 参数为空的时候
                var Cookie = document.cookie.split('; ');  // 获取所有cookie,并通过'; '存入数组当中;
                Cookie.forEach(function(val,index){
                    var value = val.split('=')[0]; // 遍历数组获取名字
                    document.cookie = value+'="";expires=' + new Date().toGMTString();  // 删除cookie
                });
            }
        }
    };
    win.GD16 = GD16; //挂载
})(window,document);

以下是“老司机”代码:

(function (win,doc) {
    var GD16 = {
        /**
         * 设置cookie|删除cookie|修改cookie
         */
        setCookie: function (name, value, time) {
            var d = new Date(new Date().getTime() + time * 1000).toGMTString();
            document.cookie = '' + name + '=' + value + ';expires=' + d;
        },
        /**
         * 获取cookie
         * @param name
         * @returns {string}
         */
        getCookie: function (name) {
            var arr = document.cookie.split('; ');
            var value = '';
            for (var i = 0, len = arr.length; i < len; i++) {
                if (arr[i].split('=')[0] == name) {
                    value = arr[i].split('=')[1];
                    break;
                }
            }
            return value;
        }
    };
    win.GD16 = GD16;
})(window,document);

  在下不得不说佩服佩服,相信已经能看出区别在哪了,我的思路有一个致命的缺点,忽略了失效的时间(time),而且代码看起来很是臃肿;

  在以后码代码的过程中,思考范围还要扩大些,还是要多虚心学习

转载于:https://www.cnblogs.com/Sheng-tobacco/p/6928949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值