gpt4 book ai didi

javascript - 在类外部定义变量与将其用作类内部的属性

转载 作者:行者123 更新时间:2023-12-01 00:51:37 25 4
gpt4 key购买 nike

我不确定 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;

最佳答案

关注the advice I already gave ,您可以简单地将 cookieExists 定义为 ieAlert 的属性。如果您希望属性访问每次都重新评估条件,则将其定义为 getter property :

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;

关于javascript - 在类外部定义变量与将其用作类内部的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56923781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com