add a method to a subclass in javascript

To add a method to a subclass in JavaScript, you can use the prototype property of the subclass constructor. Here is an example:

index.tsx
// Define the superclass
class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

// Define the subclass
class Dog extends Animal {
  constructor(name) {
    super(name);
  }
}

// Add a method to the subclass
Dog.prototype.bark = function() {
  console.log(this.name + ' barks.');
};

// Create an instance of the subclass
let d = new Dog('Rex');
d.speak(); // Output: "Rex makes a noise."
d.bark(); // Output: "Rex barks."
501 chars
28 lines

In this example, we first define the Animal superclass with a speak method. Then, we define the Dog subclass that extends the Animal class. Finally, we use the prototype property of the Dog subclass to add a bark method. We can then create an instance of the Dog subclass and call both the speak and bark methods.

gistlibby LogSnag