我昨天呢,把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),而且代码看起来很是臃肿;

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