使用构造函数的方式 再找到构造函数的原型上面封装Cookie
使用Cookie构造函数创建Cookie实例化对象
var cookie = new Cookie();
封装了Cookie的四个函数:
1:setCookie("键","值","有效时间"):设置Cookie;
2:getCookie("键") :获取Cookie 具有返回值;
3:removeCookie("键"):删除Cookie;
4:clearCookie( ):清空Cookie;
prototypeCookie.js:
// Cookie构造函数
function Cookie() {}
// 创建Cookie
// setCookie("键","值","有效时间")
Cookie.prototype.setCookie = function (key, value, time) {
var now = new Date();
now.setDate(now.getDate() + time);
document.cookie = `${key} = ${value}; expires = ${now}`;
};
// 获取Cookie
// getCookie("键")
Cookie.prototype.getCookie = function (key) {
var str = document.cookie;
var nweArray1 = str.split("; ");
for (var item of nweArray1) {
var newArray2 = item.split("=");
if (newArray2[0] == key) {
// console.log(newArray2[1]);
return newArray2[1];
}
}
};
// 删除Cookie
// removeCoolie("键")
Cookie.prototype.removeCookie = function (key) {
this.setCookie(key, "", -1);
};
// 清空Cookie
// clearCookie()
Cookie.prototype.clearCookie = function () {
var str = document.cookie;
var newArray1 = str.split("; ");
for (var item of newArray1) {
var newArray2 = item.split("=");
this.setCookie(newArray2[0], "", -1);
}
};