Prototype Pattern
Share properties among many objects of the same type
Overview
If we want to share properties among many objects of the same type, we can use the Prototype pattern.
Implementation
Say we wanted to create many dogs with a createDog
factory function.
This way, we can easily create many dog objects with the same properties.
However, we're unnecessarily adding a new bark
and wagTail
methods to each dog object. Under the hood, we're creating two new functions for each dog object, which uses memory.
We can use the Prototype Pattern to share these methods among many dog objects.
ES6 classes allow us to easily share properties among many instances, bark
and wagTail
in this case.
Tradeoffs
✔ Memory efficient: The prototype chain allows us to access properties that aren't directly defined on the object itself, we can avoid duplication of methods and properties, thus reducing the amount of memory used.
⚠️ Readaibility: When a class has been extended many times, it can be difficult to know where certain properties come from.
For example, if we have a BorderCollie class that extends all the way to the Animal class, it can be difficult to trace back where certain properties came from.
Exercise
Challenge
Refactor this factory function to a class.