Classes make it easy to create multiple objects that share property names and methods.
To create a new class, we use class
keyword. The class keyword is followed by a CamelCased class name. We always add the constructor() method.
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
Class method and getter syntax is the same as it is for objects except you can not include commas between methods.
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
To create a class inheritance, we use the extends
keyword.
The subclass inherits all of the parent’s getters, setters, and methods.
The super
keyword is used in subclasses to call a parent constructor().
For each subclass, we can also add add getters, setters, and methods.
For example, we can extend Animal to the subclass Cat.
class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
get usesLitter() {
return this._usesLitter;
}
}
An instance is an object that contains the property names and methods of a class, but with unique property values.
For example, to create a new Cat, we use keyword new
const milkCat = new Cat('Milk', false);
the static
keyword defines a static method for a class.
Static methods are not called on individual instances of the class, but are called on the class itself.
static generatePassword() {
return Math.floor(Math.random() * 10000);