Inheritance in JavaScript
Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and methods from another class. In JavaScript, inheritance is achieved through prototype chaining.
Defining a Parent Class:
To create a parent class in JavaScript, you can use a constructor function or a class declaration.
Constructor Function:
javascriptfunction Animal(name) {
  this.name = name;
}
Animal.prototype.sayHello = function() {
  console.log('Hello, my name is ' + this.name);
};
Class Declaration:
javascriptclass Animal {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log('Hello, my name is ' + this.name);
  }
}
Defining a Child Class:
To create a child class that inherits from a parent class, you can use the Object.create() method or the extends keyword with class declarations.
Using Object.create():
javascriptfunction Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
  console.log('Woof!');
};
Using extends Keyword:
javascriptclass Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
  bark() {
    console.log('Woof!');
  }
}
Creating Instances:
You can create instances of the parent and child classes and invoke their methods.
javascriptconst animal = new Animal('Generic Animal');
animal.sayHello(); // Output: Hello, my name is Generic Animal
const dog = new Dog('Buddy', 'Labrador');
dog.sayHello(); // Output: Hello, my name is Buddy
dog.bark(); // Output: Woof!
Explanation:
- The parent class (Animal) defines a common behavior, such as thesayHellomethod.
- The child class (Dog) inherits from the parent class using eitherObject.create()or theextendskeyword.
- In both cases, the child class has access to the parent class's properties and methods.
- When using Object.create(), we ensure that the child class prototype points to the parent class prototype.
- In the class declaration, the superkeyword is used to call the parent class constructor and access its properties and methods.
- The child class can also have its own additional properties and methods.
- Instances of both the parent and child classes can be created, and their methods can be invoked.
 
 
 
0 Comments