Explain inheritance in javascript with example and output
视频信息
答案文本
视频字幕
Welcome to JavaScript inheritance! Inheritance is a fundamental concept in object-oriented programming that allows objects to inherit properties and methods from other objects. JavaScript uses prototype-based inheritance, where objects can inherit from other objects through the prototype chain. In this example, we'll see how a Dog class can inherit from an Animal parent class using the extends keyword and super method.
Let's start by creating the parent class called Animal. This class has a constructor that takes a name parameter and stores it as a property. It also has two methods: eat and sleep. The eat method returns a string saying the animal is eating, and the sleep method returns a string saying the animal is sleeping. These properties and methods will be inherited by any child class that extends Animal.
Now let's create the Dog class that inherits from Animal. We use the extends keyword to specify that Dog inherits from Animal. In the constructor, we call super with the name parameter to initialize the parent class. We then add a new property called breed. The Dog class also has its own bark method that returns a woofing sound. Notice how we override the sleep method but still call the parent's sleep method using super dot sleep, then add our own zzz sound.
Let's create an instance of the Dog class and see inheritance in action. We create a new Dog object called myDog with the name Buddy and breed Golden Retriever. We can access the name property which was inherited from the Animal class, and the breed property which is specific to the Dog class. We can call the eat method inherited from Animal, the bark method specific to Dog, and the overridden sleep method that combines both parent and child behavior.
Here's the output when we run our inheritance example. We can see that Buddy has access to both inherited properties like name, and new properties like breed. The methods work as expected: eat is inherited from Animal, bark is specific to Dog, and sleep shows method overriding in action. JavaScript inheritance provides code reusability, creates hierarchical relationships between objects, enables method overriding, supports extensible design patterns, and results in cleaner, more organized code structure.