classes
?Classes are in fact special functions, and just as you can define function expressions and function declarations
, the class syntax has two components: class expressions and class declarations.
Reference Material:
MDN
Example:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
classes
?Classes inherit via the extends
keyword. extends
tells the new class that you create that it is the child of the following class name. Once a class is extended you also need to use the super()
function to tell the parent class that it now has a child.
Example:
// Parent class
class Animals {
constructor(attributes) {
this.animalCommonName = attributes.animalCommonName;
this.weight = attributes.weight;
this.height = attributes.height;
this.food = attributes.food;
}
eat() {
return `The ${this.animalCommonName} eats ${this.food}`;
}
}
// Child class
// Extends: "Hey, Dog, Animals is your parent! Grab everything from them."
// super(): "Hey, Animals, Dog is your child, give them everything they need."
class Dog extends Animals {
constructor(dogAttribs) {
super(dogAttribs);
this.name = dogAttribs.name;
this.bark = dogAttribs.bark;
}
speak() {
return `${this.name} says: ${this.bark}`;
}
}