想把cookie操作用proxy封装,原代码如下:
const cookie = (name, value, options = {}) => {
if (value !== void 0) {
let s = name + '=' + encodeURIComponent(value);
if (options.expires && (typeof options.expires == 'number' ||
options.expires.toUTCString))
{
let date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(options.expires * 24 * 3600000 + date.getTime());
} else {
date = options.expires;
}
s += '; expires=' + date.toUTCString();
}
//options: expires,path,domain,secure
delete options.expires;
for (const k in options) s += '; ' + k + '=' + options[k];
document.cookie = s;
} else {
let s = ''+ document.cookie;
const head = name + '=';
s = s.split(/\s*;\s*/).find(k => k.startsWith(head));
return s && decodeURIComponent(s.slice(name.length + 1));
}
};
封装后代码,重点看注释行:
const cookie = new Proxy({}, {
get(target, name) {
// 正常读取属性, name永远为字符串
// if (typeof name == 'string') { //如何判断?
// let s = ''+ document.cookie;
// const head = name + '=';
// s = s.split(/\s*;\s*/).find(k => k.startsWith(head));
// return s && decodeURIComponent(s.slice(name.length + 1));
// }
return function (value, options = {}) {
if (value == null) {
value = '';
options.expires = -1;
}
let s = name + '=' + encodeURIComponent(value);
options.expires = options.expires || 6;
if (options.expires && (typeof options.expires == 'number' ||
options.expires.toUTCString))
{
let date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(options.expires * 24 * 3600000 + date.getTime());
} else {
date = options.expires;
}
s += '; expires=' + date.toUTCString();
}
delete options.expires;
for (const k in options) s += '; ' + k + '=' + options[k];
document.cookie = s;
}
}
});
// cookie.cna; //正常读属性
cookie.cna('dfafdda'); //写cookie