JS面向对象编程 for Cookie

前一些天做项目的时候写了一个通用的OO By Class Cookie

今天把它放上来给大家分享下!

各位如果有更好的见解可讨论下!

 

JS CODE
1 /*
2 * Js Class Cookie
3 * Author:Mr Co
4 */
5  var Cookie = function(/*Cookie名称*/name){
6
7 this.$name = name;
8
9 var allcookies = document.cookie;
10
11 if(allcookies == '') return;
12
13 var cookies = allcookies.split(';');
14
15 var cookie = null;
16
17 for(var i = 0; i < cookies.length; i++){
18
19 if(cookies[i].substring(0,name.length + 1) == (name + '=')){
20
21 cookie = cookies[i];
22
23 break;
24
25 }
26
27 }
28
29 if(cookie == null) return;
30
31 var cookieval = cookie.substring(name.length + 1);
32
33 var a = cookieval.split('&');
34
35 for(var i = 0; i < a.length; i++){
36
37 a[i] = a[i].split(':');
38
39 }
40
41 for(var i = 0; i < a.length; i ++){
42
43 this[a[i][0]] = decodeURIComponent(a[i][1]);
44
45 }
46 }
47
48  /*
49 * 保存Cookie数据对象
50 */
51 Cookie.prototype.store = function(/*过期时间(1表示一天以此类推)*/daysToLive,/*当前Cookie有效地址*/path,/*当前Cookie有效域名访问*/domain,/*安全性*/secure){
52
53 var cookieval = '';
54
55 for(var prop in this){
56
57 if((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) continue;
58
59 if(cookieval != '') cookieval += '&';
60
61 cookieval += prop + ':' + encodeURIComponent(this[prop]);
62
63 }
64
65 var cookie = this.$name + '=' + cookieval;
66
67 if(daysToLive || daysToLive == 0){
68
69 cookie += '; max-age=' + (daysToLive * 24 *60 *60);
70
71 }
72
73 if(path) cookie += '; path=' + path;
74
75 if(domain) cookie += ';domain=' + domain;
76
77 if(secure) cookie += ';secure';
78
79 document.cookie = cookie;
80
81 }
82
83  /*
84 * 移除Cookie数据对象指定属性
85 */
86 Cookie.prototype.remove = function(/*当前Cookie有效地址*/path,/*当前Cookie有效域名访问*/domain,/*安全性*/secure){
87
88 for(var prop in this){
89
90 if(prop.charAt(0) != '$' && typeof this[prop] != 'function') delete this[prop];
91
92 }
93
94 this.store(0,path,domain,secure);
95
96 }
97
98 /*
99 * 验证当前客户端浏览器是否支持Cookie
100 */
101 Cookie.IsAllowCookie = function(){
102
103 if(!navigator.cookieEnabled){
104
105 alert('温馨提示:\r\n  您的浏览器当前已禁用页面Cookie!这可能会导致您在\r\n\r\n选择食物数据的时候刷新页面丢失您已选择的食物数据!\r\n\r\n建议您启用浏览器Cookie!');
106
107 return false;
108
109 }
110
111 return true;
112
113 }

 

 

测试JS DEMO
1 function testFn(){
2
3 var cookie = new Cookie('Test');
4
5 if(!cookie.name || !cookie.color){
6
7 cookie.name = prompt('What is your name:','');
8
9 cookie.color = prompt('What is your favorite color:','');
10
11 }
12
13 if(!cookie.visits) cookie.visits = 1;
14 else cookie.visits++;
15
16 cookie.store(10);
17
18 alert('color:' + cookie.color + ' name:' + cookie.name + ' visits:' + cookie.visits);
19
20 }

 

posted @ 2010-09-19 10:11  MR CO  阅读(555)  评论(0编辑  收藏  举报