How does prototypal inheritance work in JavaScript?
Asked on Aug 04, 2024
Answer
Prototypal inheritance in JavaScript allows objects to inherit properties and methods from other objects. This is achieved through the prototype chain, where objects have a "prototype" property that points to another object, enabling shared functionality.
// Create a prototype object
const animal = {
speak() {
console.log("Animal sound");
}
};
// Create a new object that inherits from animal
const dog = Object.create(animal);
// Add a new method to the dog object
dog.bark = function() {
console.log("Woof!");
};
// Test the inheritance
dog.speak(); // Inherited method
dog.bark(); // Own method
Additional Comment:
✅ Answered with JavaScript best practices.- The "animal" object serves as a prototype with a "speak" method.
- The "dog" object is created using "Object.create(animal)", inheriting from "animal".
- "dog" has its own method "bark" and also inherits "speak" from "animal".
- This demonstrates how objects can share functionality through their prototype.
Recommended Links:
← Back to All Questions