Ask any question about JavaScript here... and get an instant response.
How can I override a method in a prototype chain without affecting other instances in JavaScript?
Asked on Nov 19, 2025
Answer
To override a method in a prototype chain without affecting other instances, you can define the method directly on the instance itself. This ensures that only the specific instance has the overridden method, while other instances remain unaffected.
<!-- BEGIN COPY / PASTE -->
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return `${this.name} makes a noise.`;
};
const dog = new Animal('Dog');
const cat = new Animal('Cat');
// Override the speak method for the dog instance only
dog.speak = function() {
return `${this.name} barks.`;
};
console.log(dog.speak()); // "Dog barks."
console.log(cat.speak()); // "Cat makes a noise."
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "Animal" function is a constructor that sets up a prototype with a "speak" method.
- The "dog" instance has its "speak" method overridden, affecting only this instance.
- The "cat" instance still uses the original "speak" method from the prototype.
- This approach ensures that changes are isolated to the specific instance.
Recommended Links:
