Sobes.tech
Junior — Middle

Can you explain how one class can inherit properties and methods from another class?

sobes.tech AI

Answer from AI

In JavaScript (and Node.js), inheritance is implemented using prototypes or classes (ES6+). To have one class inherit properties and methods from another, the extends keyword is used.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Sharik');
dog.speak(); // Outputs: Sharik barks.

Here, the Dog class inherits properties and methods from the Animal class, and can override methods or add new ones.

Can you explain how one class can inherit properties… - sobes.tech