Everyone seems to generally agree that prototype inheritance is simpler and more flexible than class inheritance. What I have not seen in the literature that I've read is very many examples of things that you can do with prototype inheritance that you cannot with classical. So I pose a simple question:
What are some patterns that you can use with prototype inheritance that you cannot with class inheritance and what is the guidance you would give as far when/if to use it?
One difference (perhaps at least conceptually) is that class inheritance implies that the child IS-A type of the parent. Prototype inheritance makes no such implication; a mammal is a prototype for a cat (the Merriam-Webster definition says this means it's a "pattern for"), but nothing else. A cat is free remove/add/change behaviors as it sees fit.
Ok, I'll add one, use the fact that prototype links are live to monkey-patch methods for a whole class of objects:
var Cat = function(catName) {
this.catName = catName;
};
Cat.prototype.meow = function() {
console.log(this.catName+" says meow");
}
var mittens = new Cat("Mittens");
var whiskers = new Cat("Whiskers");
mittens.meow(); // "Mittens says meow"
whiskers.meow(); // "Whiskers says meow"
// All cats are now angry
Cat.prototype.meow = function() {
console.log(this.catName+" says hissssss");
}
mittens.meow(); // "Mittens says hissssss"
whiskers.meow(); // "Whiskers says hissssss"
This would be useful if you have objects that suddenly need to start acting in a completely different yet consistent manner in response to some sort of global event. Maybe for something like:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With