-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses-inheritance-I.js
71 lines (60 loc) · 2.25 KB
/
classes-inheritance-I.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* 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.
*/
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() { // static method not available to subclasses
return Math.floor(Math.random() * 10001);
}
};
// extend parent class HospitalEmployee to subclass Nurse
class Nurse extends HospitalEmployee {
constructor(name, certifications) {
super(name); // `super` must be called before `this`
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); // 15
nurseOlynyk.addCertification('Genetics');
console.log(nurseOlynyk.certifications); // ['Trauma', 'Pediatrics', 'Genetics']
// Note: The subclass inherits all of the parent’s getters, setters, and methods. You can also use the `super` keyword to set properties in the parent class.
class Doctor extends HospitalEmployee {
constructor(name, insurance) {
super(name); // `super` must be called before `this`
this._insurance = insurance;
}
get insurance() {
return this._insurance;
}
};
const doctorHeisen = new Doctor('Bill', false);
console.log(doctorHeisen.name); // Bill
console.log(doctorHeisen.insurance); // false
doctorHeisen.takeVacationDays(20);
console.log(doctorHeisen.remainingVacationDays); // 0
console.log(HospitalEmployee.generatePassword());