Calling an Overridden Method in OOP in JavaScript
When overridden, the child loses access to the overridden method of the parent. However, it can still be accessed. This is done using the super
keyword, which points to the parent class.
Let's look at an example where we might need access to a parent method. Let's say we have the following parent class:
class User {
setName(name) {
this.name = name;
}
getName() {
return this.name;
}
}
Let's say we override the parent's method in the child class:
class Student extends User {
setName(name) {
if (name.length > 0) {
this.name = name;
} else {
throw new Error('student name error');
}
}
}
You can see that in the overridden method, when the condition is met, the code of the parent method is actually executed. This results in unnecessary duplication of code.
We can get rid of it by calling the parent's method. Let's do that:
class Student extends User {
setName(name) {
if (name.length > 0) {
super.setName(name); // parent method
} else {
throw new Error('student name error');
}
}
}
The following code is given:
class User {
setAge(age) {
if (age >= 0) {
this.age = age;
} else {
throw new Error('need age more 0');
}
}
}
class Employee {
setAge(age) {
if (age <= 120) {
if (age >= 0) {
this.age = age;
} else {
throw new Error('need age more 0');
}
} else {
throw new Error('need age less 120');
}
}
}
In class Employee
, fix the simplify age setter by using the original parent method.