Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are patterns you could use with prototype inheritance that you cannot with class?

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?

like image 536
George Mauer Avatar asked Jun 07 '11 14:06

George Mauer


2 Answers

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.

like image 112
Esteban Araya Avatar answered Sep 27 '22 02:09

Esteban Araya


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:

  • Themes and skinning
  • Whether a page is functioning in "online mode" or "offline mode" (while online all queries are stored/retrieved via ajax, while offline queries redirect to browser storage)
like image 38
George Mauer Avatar answered Sep 25 '22 02:09

George Mauer