Introduction to Classes
Classes are a tool that developers use to quickly produce similar objects.
Class example with constructor & call new class instance
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
} incrementBehavior() {
this._behavior++;
}
}
const halley = new Dog(‘Halley’);
What must call on the first line of subclass constructors?
super(name);
example:
class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
}Review: Classes
Classes are templates for objects. Javascript calls a constructor method when we create a new instance of a class. Inheritance is when we create a parent class with properties and methods that we can extend to child classes. We use the extends keyword to create a subclass. The super keyword calls the constructor() of a parent class. Static methods are called on the class, but not on instances of the class.
Example:
Parent & Child class:
class Nurse extends HospitalEmployee {}class HospitalEmployee {
constructor(name) {
this._name = name;
this._remainingVacationDays = 20;
}
get name() {
return this._name;
}
get remainingVacationDays() {
return this._remainingVacationDays;
}
takeVacationDays(daysOff) {
this._remainingVacationDays -= daysOff;
}
static generatePassword() {
return Math.floor(Math.random() * 10000);
}
}
class Nurse extends HospitalEmployee {
constructor(name, certifications) {
super(name);
this._certifications = certifications;
} get certifications() {
return this._certifications;
}addCertification(newCertification) {
this.certifications.push(newCertification);
}
}
const nurseOlynyk = new Nurse(‘Olynyk’, [‘Trauma’,’Pediatrics’]);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);
nurseOlynyk.addCertification(‘Genetics’);
console.log(nurseOlynyk.certifications);