javascript - 在类外部定义变量与将其用作类内部的属性
问题描述
我不确定ieAlert类之外的cookieExists的定义。变量cookieExists在ieAlert类之外可以吗?或者我应该将它定义为类定义中的一个属性?
var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;
class ieAlert {
// Method for checking if IE11
static isIE() {
return window.navigator.userAgent.match(/(MSIE|Trident)/);
}
// Method for setting a cookie
static createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
}
if (!ieAlert.isIE() && !cookieExists) {
window.alert("Your browser is outdated!");
ieAlert.createCookie('myCookie', 'ie11_cookie', 1);
}
module.exports = ieAlert;
解决方案
按照我已经给出的建议,您可以简单地定义cookieExists
为ieAlert
. 如果您希望属性访问每次都重新评估条件,则将其定义为getter 属性:
const ieAlert = {
// Method for checking if IE11
isIE () {
return /MSIE|Trident/.test(window.navigator.userAgent);
},
get cookieExists () {
return document.cookie.includes('ie11_cookie');
},
// Method for setting a cookie
createCookie (name, value, days) {
const cookie = [`${name}=${value}`, 'path=/'];
if (days) {
const date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
cookie.splice(1, 0, `expires=${date.toGMTString()}`);
}
document.cookie = cookie.join('; ');
}
};
if (!ieAlert.isIE() && !ieAlert.cookieExists) {
window.alert("Your browser is outdated!");
// ieAlert.cookieExists === false
ieAlert.createCookie('myCookie', 'ie11_cookie', 1);
// ieAlert.cookieExists === true
}
module.exports = ieAlert;
推荐阅读
- r - 使特定列成为 r 中的标题(重塑/转置)
- javascript - 插入数据库的 Ajax 调用不起作用
- python-3.x - 从字节串伪造 scapy 数据包
- ios - 具有 2 个数据集的多折线图
- java - ArrayList 构造函数错误
- django - 如何记录 Django REST Framework 文档的响应模式?
- php - 使用 !empty 检查变量是否为空的区别
- javascript - 地图中两点之间的距离
- influxdb - InfluxDB:从零开始cumulative_sum()/对cumulative_sum和non_negative_difference所需的聚合分组
- jquery - Asp.net Mvc ajax 动作提交两次