Subclassing
So far, we discussed how to declare classes and the types of members classes can support. A major use of a class is to serve as a template to create other subclasses. When you create a child class from a class, you derive properties of the parent class and extend the parent class by adding more features of its own.
Let's look at the following de facto example of inheritance:
class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' generic noise'); } } class Cat extends Animal { speak() { console.log(this.name + ' says Meow.'); } } var c = new Cat('Grace'); c.speak();//"Grace says Meow."
Here, Animal
is the base class and the Cat
class is derived from the class Animal
. The extend clause allows you to create a subclass of an existing class. This example demonstrates the syntax...