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;
Assuming you never instantiate
ieAlert
(e.g.new ieAlert()
is never used), then you're misusingclass
. 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 astatic
method ofArray
. It would not make sense to defineisArray()
as non-static, because that would require you to already have an instance ofArray
, 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:
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.
However, with a static keyword you could say.
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.