To extend a JavaScript class, we can use the extends
keyword and the class syntax.
For instance, we can write:
class Person {
sayHello() {
console.log('hello');
}
walk() {
console.log('I am walking!');
}
}
class Student extends Person {
sayGoodBye() {
console.log('goodbye');
}
sayHello() {
console.log('Hi, I am a student');
}
}
const student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
console.log(student1 instanceof Person);
console.log(student1 instanceof Student);
We have the Person
class that serves as the base class for the Student
class.
It has the sayHello
and walk
methods.
Then we have the Student
class which inherits the contents of the Person
class.
It also has its own methods, which are sayGoodBye
and sayHello
.
The extends
keywords indicates that Student
has Person
as its base class, so it should also inherit methods from the Person
class.
Next, we create a new Student
instance with the new
keyword.
And we call all the methods from the Student
class itself and the Person
class from student1
.
Also, both console logs should log true
because student1
is a Student
instance and Student
‘s base class is Person
.