jquery-cookie v1.4源码解析

一、主体代码结构

二、源码分析

1、简化结构分析

 1 (function(factory){
 2     
 3     //check global env  
 4     factory(jQuery);
 5     
 6 })(function($){
 7     
 8     // uri编码
 9     function encode(){}
10     
11     // uri解码
12     function decode(){}
13     
14     // json转string
15     function stringifyCookieValue(){}
16     
17     // string转json
18     function parseCookieValue(){}
19     
20     // 读取
21     function read(){}
22     
23     // 删除
24     function removeCookie(){}
25     
26 });

2. 核心函数分析

 1 var config = $.cookie = function (key, value, options) {
 2 
 3     // 写入 cookie document.cookie = 'xxx'
 4     if (value !== undefined && !$.isFunction(value)) {
 5         options = $.extend({}, config.defaults, options);
 6 
 7         if (typeof options.expires === 'number') {
 8             var days = options.expires, t = options.expires = new Date();
 9             t.setDate(t.getDate() + days);
10         }
11 
12         return (document.cookie = [
13             encode(key), '=', stringifyCookieValue(value),
14             options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
15             options.path    ? '; path=' + options.path : '',
16             options.domain  ? '; domain=' + options.domain : '',
17             options.secure  ? '; secure' : ''
18         ].join(''));
19     }
20 
21     // 1. 只有一个key时,是读取cookie 2. key,value都存在,但value是一个转换函数
22     var result = key ? undefined : {};
23 
24     // 读取cookie,遍历 命令 key时返回结果
25     var cookies = document.cookie ? document.cookie.split('; ') : [];
26 
27     for (var i = 0, l = cookies.length; i < l; i++) {
28         var parts = cookies[i].split('=');
29         var name = decode(parts.shift());
30         var cookie = parts.join('=');
31 
32         if (key && key === name) {
33             // If second argument (value) is a function it's a converter...
34             result = read(cookie, value);
35             break;
36         }
37 
38         // Prevent storing a cookie that we couldn't decode.
39         if (!key && (cookie = read(cookie)) !== undefined) {
40             result[name] = cookie;
41         }
42     }
43 
44     return result;
45 };

 3. 转换函数读取文件

1 function read(s, converter) {
2         var value = config.raw ? s : parseCookieValue(s);
3         return $.isFunction(converter) ? converter(value) : value;
4     }

 

posted @ 2020-12-14 16:44  pengsn  阅读(194)  评论(0编辑  收藏  举报