Why do I need static keyword here

2019-07-24 19:03发布

I'm trying to understand class and class methods in JavaScript.

The bellow example, works only if you add the keyword static before isIE() method.

1. Why do I need static keyword?

2. How should I change the function, so that I don't need to use static?

class ieAlert {
  // Method for checking if IE11
  static isIE() {  
    return window.navigator.userAgent.match(/(MSIE|Trident)/);
  }
}
// If the user is using IE11, show the alert
if (ieAlert.isIE()) {
  window.alert("Your browser is outdated!");
}

module.exports = ieAlert;

2条回答
ら.Afraid
2楼-- · 2019-07-24 19:21

Assuming you never instantiate ieAlert (e.g. new ieAlert() is never used), then you're misusing class. Classes should be used for defining a type that describes the behavior for many objects that function independently and use the same common methods.

The reason static is required is because you're trying to define a function that does not operate from one of these many instantiated objects, but rather from the class itself.

For example, Array.isArray() is a static method of Array. It would not make sense to define isArray() as non-static, because that would require you to already have an instance of Array, and you don't know if what you have is an array yet.

In this case, you just need to define an object with a method:

const ieAlert = {
  // Method for checking if IE11
  isIE () {  
    return /MSIE|Trident/.test(window.navigator.userAgent);
  }
}

// If the user is using IE11, show the alert
if (ieAlert.isIE()) {
  window.alert('Your browser is outdated!');
}

module.exports = ieAlert;
查看更多
劳资没心,怎么记你
3楼-- · 2019-07-24 19:33

The reason why you need a static keyword there is because you're accessing a class or an object's method without instantiating or creating the class.

For example, if the method wasn't static you would say.

//CREATE NEW INSTANCE
let dog = new Dog()
//ACCESS METHOD
dog.bark()

However, with a static keyword you could say.

//ACCESS METHOD WITHOUT        CREATING INSTANCE
 Dog.bark()

Without having to create a NEW instance of the class.

There are pros and cons to both of this methods that you should be aware of.

For example, a static variable only has one sole instance, and therefore its value will be same for every class that has access to it.

So, if you want to have 10 dogs and each of them has a different breed you wouldn't use a static variable.

This is common knowledge, it doesn't matter what programming language you're using. I suggest you find a good JavaScript tutorial.

查看更多
登录 后发表回答