首页 > 解决方案 > 在类外部定义变量与将其用作类内部的属性

问题描述

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

标签: javascriptclass

解决方案


按照我已经给出的建议,您可以简单地定义cookieExistsieAlert. 如果您希望属性访问每次都重新评估条件,则将其定义为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;

推荐阅读