将函数转换为类

时间:2019-07-05 08:22:01

标签: class cookies alert

以下代码显示了警告,如果用户使用的是IE11并设置了24小时后过期的Cookie:

var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;

// Function for checking if IE11 or bellow
function isIE() {  
  return window.navigator.userAgent.match(/(MSIE|Trident)/);
}

// Function for setting a cookie
function 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 the user is using IE11 and no cookie exist, show the alert and set a cookie
if (isIE() && !cookieExists) {
  window.alert("Your browser is outdated!");
  // Setting a cookie with an expiry date of 1 day
  createCookie('myCookie', 'ie11_cookie', 1);
}

该脚本有效,但现在我正尝试将其转换为类。 我已经尝试过了:

var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;

class ieAlert {
  // Method for checking if IE11 or bellow
  isIE() {  
    return window.navigator.userAgent.match(/(MSIE|Trident)/);
  }
  // Method for setting a cookie
  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 the user is using IE11 and no cookie exist, show the alert and set a cookie
if (ieAlert.isIE() && !cookieExists) {
  window.alert("Your browser is outdated!");
  // Setting a cookie with an expiry date on 1 day
  createCookie('myCookie', 'ie11_cookie', 1);
}

module.exports = ieAlert;

但是,如果我运行代码,则会在控制台中收到以下错误:

  

未捕获的TypeError:ieAlert.isIE不是函数

我也不想使用任何ES6语法,因为该脚本应在IE11中运行,并且我不使用Babel。

我在做什么错?正确的解决方案是什么?

1 个答案:

答案 0 :(得分:1)

如果您不想在类的实例上调用函数,而是在类本身上调用函数,则应使用static关键字将isIE函数定义为静态。

var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;
class ieAlert {
  static isIE() {  
    return window.navigator.userAgent.match(/(MSIE|Trident)/);
  }
  // …
}
// …
if (ieAlert.isIE() && !cookieExists) {
  // …
}