What are object prototypes in JavaScript?
Asked on Aug 03, 2024
Answer
Object prototypes in JavaScript are a mechanism by which objects inherit properties and methods from other objects. This allows for shared functionality across instances.
// Create a prototype object
const animal = {
speak() {
console.log("Animal speaks");
}
};
// Create a new object that inherits from the animal prototype
const dog = Object.create(animal);
dog.speak(); // Output: Animal speaks
Additional Comment:
✅ Answered with JavaScript best practices.- The "animal" object acts as a prototype for the "dog" object.
- "dog" inherits the "speak" method from "animal".
- "Object.create" is used to create a new object with a specified prototype.
- Prototypes allow for efficient method sharing across multiple objects.
Recommended Links:
← Back to All Questions