cookie自封装对象

时间:2025-03-27 11:05:25

cookie.js(设置名值对属性时候不支持设置成前后有空格的格式,如' key'或'key ',只支持‘key’)

(function initCookieClass(win){// 定义匿名函数并在定以后立即调用(function(){}()),圆括号保证并正确解析成函数
var Cookie=function Cookie(maxage,path){// Cookie构造函数
// 私有属性,将document.cookie解析成JSON对象
var cookie=(function(ck){
var cookie={};
var all=ck;
if(all==='') return cookie; // 返回空值对象
// document.cookie以key1=value1;key2=value2的格式存储数据
var list=all.split(';');
for (var i = 0; i < list.length; i++) {
var c=list[i];
var p=c.indexOf('=');
var name=c.substring(0,p);
// cookie存储中第一个名值对没有空格,第二个开始都有空格,做清除空格操作
if(name && typeof name==='string') name=name.replace(/^\s|\s%/,'');
var value=c.substring(p+1);
// 对名值对进行解码,一般只要对值进行编解码,主要是对中文的处理
name=decodeURIComponent(name);
value=decodeURIComponent(value);
cookie[name]=value;
}
return cookie;
}(win.document.cookie));
// 私有属性,keysSet
var keys=[];
for(var key in cookie) keys.push(key);
// 自有属性,length表示cookie的对象数
this.length=keys.length;
// 实例方法,根据索引值返回cookie值,在根据长度遍历时候使用
this.key=function(n){
if(n<0||n>keys.length) return null;
return cookie[n];
};
// 实例方法,根据key获取value
this.getItem=function(name){
return cookie[name]||null;
};
// 实例方法,设置cookie属性,以名值对的格式
this.setItem=function(key,value){
if(!key) {
for(var k in value) {
this.setItem(k, value[k]);
}
return;
}
if(!(key in cookie)) {
keys.push(key);
this.length++;
}
cookie[key]=value;
var c=encodeURIComponent(key)+'='+encodeURIComponent(value);
if(maxage) c+=';max-age='+maxage;
if(path) c+=';path='+path;
win.document.cookie=c;
return this;
};
// 实例方法,根据key删除value
this.removeItem=function(key){
if(!(key in cookie)) return;
delete cookie[key];
for (var i = 0; i < keys.length; i++) {
if(keys[i]===key) {
keys.splice(i,1);
break;
}
}
this.length--;
win.document.cookie=encodeURIComponent(key)+'=;max-age=0';
return this;
};
// 实例方法,清除掉cookie数据和此对象数据
this.clear=function(){
for (var i = 0; i < keys.length; i++) {
win.document.cookie=encodeURIComponent(keys[i])+'=;max-age=0';
}
cookie={};
keys=[];
this.length=0;
return this;
};
// 实例方法,重新从浏览器中获取cookie数据
this.sync=function(){
cookie=(function(){
var cookie={};
var all=win.document.cookie;
if(all==='') return cookie;
var list=all.split(';');
for (var i = 0; i < list.length; i++) {
var c=list[i];
var p=c.indexOf('=');
var name=c.substring(0,p);
if(name && typeof name==='string') name=name.replace(/^\s|\s%/,'');
if(name) name=name.replace(/^\s|\s%/,'');
var value=c.substring(p+1);
name=decodeURIComponent(name);
value=decodeURIComponent(value);
cookie[name]=value;
}
return cookie;
}());
keys=[];
for(var key in cookie) keys.push(key);
this.length=keys.length;
return this;
};
// 实例方法,返回cookie的JSON格式
// 因为cookie是私有属性,在函数体闭包内用val声明的变量,在函数体外是无法直接访问的
this.getCookieJSON=function(){
return cookie;
};
};
win.Cookie=Cookie;
win.cookie=new Cookie();
}(window));

cookie.html,简单测试一下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cookie Test</title>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript">
(function(w){
w.onload=function(){
if(cookie) {
// 增,改
cookie.setItem('test','success');
// 查
var result=cookie.getItem('test');
console.log('test:'+result);
// 删
cookie.removeItem('test');
// 支持JSON格式的存储方案
cookie.setItem(null,{'one':1,'two':2});
// 根据JSON格式查找
result=cookie.getCookieJSON();
console.log('cookie for json:');
for(var i in result) {
console.log('\n'+i+':'+result[i]);
}
} else {
throw new Error('Create cookie instance failure.');
}
};
}(window));
</script>
</head>
<body> </body>
</html>

默认cookie对象的生命周期是Web浏览器的会话期(session),与sessionStorage的作用域不同,cookie是整个浏览器进程,而不是单个窗口的进程。不同标签页可以共用,除非显示设置。

几乎所有的浏览器都支持cookie。

参考文献:《JavaScript权威指南》  --O‘REILLY[第六版]