Welcome to JavaScript inheritance! Inheritance is a fundamental concept that allows objects to inherit properties and methods from other objects. This enables code reusability and creates hierarchical relationships between different types of objects. JavaScript uses prototype-based inheritance, and with ES6, we also have the familiar class syntax.
Let's start by creating our base class called Animal. This class has a constructor that takes a name parameter and stores it as a property. It also has two methods: speak, which logs that the animal makes a sound, and eat, which logs that the animal is eating. This will serve as our parent class that other classes can inherit from.
Now we create the Dog class that extends Animal. The extends keyword establishes inheritance. In the constructor, we call super with the name parameter to initialize the parent class, then add our own breed property. We add a new bark method, override the speak method with dog-specific behavior, and override eat to call the parent method first, then add additional behavior.
Now let's see inheritance in action. We create a Dog instance called myDog with name Buddy and breed Golden Retriever. We can access both inherited properties like name from Animal, and new properties like breed from Dog. When we call eat, it first executes the parent method, then adds dog-specific behavior. The bark method is unique to Dog, and speak is overridden. The instanceof operator confirms myDog is both a Dog and an Animal.
To summarize what we've learned about JavaScript inheritance: Inheritance enables code reusability and creates hierarchical relationships between objects. We use the extends keyword to create child classes that inherit from parent classes. The super keyword allows us to call parent constructors and methods. Child classes can override parent methods while adding their own functionality. Finally, the instanceof operator helps us verify inheritance relationships in our code.