How to use extends
on any subclass of a known baseclass?
The extends
keyword in JavaScript is used to create a class that inherits properties and methods from another class. The class that inherits is called the subclass, and the class that it inherits from is called the superclass.
To use extends
, you first need to define the superclass. The superclass should have a constructor function that takes arguments for the properties that the subclass will inherit. The constructor function should also have a super()
call, which calls the constructor function of the superclass.
<script> class Superclass { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } class Subclass extends Superclass { constructor(name, age, job) { super(name, age); this.job = job; } work() { console.log(`I am a ${this.job} and my name is ${this.name}.`); } } const person = new Subclass('John Doe', 30, 'Software Engineer'); person.greet(); // Hello, my name is John Doe and I am 30 years old. person.work(); // I am a Software Engineer and my name is John Doe. </script>
In the example above, the Superclass
class has a constructor function that takes two arguments, name
and age
. The constructor function also has a super()
call, which calls the constructor function of the Object
class.
The Subclass
class extends the Superclass
class. The constructor function of the Subclass
class takes three arguments, name
, age
, and job
. The constructor function also has a super()
call, which calls the constructor function of the Superclass
class.
The Subclass
class also has a work()
method, which is not defined in the Superclass
class. The work()
method logs a message to the console.
The person
variable is an instance of the Subclass
class. The greet()
and work()
methods are called on the person
object.
Here are some additional things to know about extends
:
- A class can only extend one other class.
- A class can implement multiple interfaces.
- A subclass inherits all of the properties and methods of its superclass.
- A subclass can override the methods of its superclass.
- A subclass can add new methods to its superclass.
extends
is a powerful tool that can be used to create complex and reusable classes.