create a subclass in javascript

In JavaScript, there are multiple ways to create a subclass. Here is an example of how to create a subclass using the prototype property:

index.tsx
// Parent class
function Animal(name, age) {
  this.name = name;
  this.age = age;
}

// Method of Parent class
Animal.prototype.getInfo = function() {
  console.log(`Name: ${this.name}, Age: ${this.age}`);
}

// Child class
function Dog(name, age, breed) {
  Animal.call(this, name, age);
  this.breed = breed;
}

// Set prototype and constructor of Child class
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// Method of Child class
Dog.prototype.getBreed = function() {
  console.log(`Breed: ${this.breed}`);
}

// Create an instance of Child class
const myDog = new Dog("Buddy", 3, "Labrador");

// Call methods of Parent class and Child class using the instance of Child class
myDog.getInfo(); // Output: Name: Buddy, Age: 3
myDog.getBreed(); // Output: Breed: Labrador
811 chars
33 lines

In this example, we have created a Parent class Animal, and a Child class Dog which extends from the Animal class using the Object.create() method. We have also created methods for both classes using the prototype property. Finally, we have created an instance of the Dog class and called methods of both Parent and Child classes using the instance.

gistlibby LogSnag