JavaScript Prototypal Inheritance Explained
JavaScript utilizes prototypal inheritance to create relationships between objects. With prototypal inheritance, objects can inherit properties and methods from other objects.
Let’s create a simple example to demonstrate prototypal inheritance:
// Define a parent object
function Animal(name) {
this.name = name;
}
// Add a method to the parent object
Animal.prototype.makeSound = function() {
console.log("Animal makes a sound");
}
// Create a child object that inherits from the parent object
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
// Add a method to the child object
Dog.prototype.bark = function() {
console.log("Dog barks");
}
// Create an instance of the child object
var myDog = new Dog("Buddy", "Golden Retriever");
// Call the inherited method
myDog.makeSound();
// Call the child method
myDog.bark();
By using prototypal inheritance, we can create a hierarchy of objects that share functionality. This is a powerful feature of JavaScript that allows for code reuse and organization.