Inheritance
Last updated
Last updated
Inheritance in JavaScript allows objects to inherit properties and methods from other objects, enabling the creation of hierarchies and the reuse of code.
One common way to achieve inheritance in JavaScript is through prototype chaining or using ES6 classes.
In this example:
Animal
is the parent constructor function defining a basic animal.
Dog
is a child constructor function inheriting from Animal
.
Object.create(Animal.prototype)
creates a new object with Animal.prototype
as its prototype, establishing the prototype chain.
Dog.prototype.constructor
sets the constructor property of Dog.prototype
to Dog
(it's reset because it was lost when setting up the prototype chain).
Here:
class
syntax provides a more structured way of defining constructors and methods.
extends
keyword allows Dog
to inherit from Animal
.
super()
is used to call the parent constructor within the child constructor.