Prototype pattern creates new objects based on an existing one with default property values.
In the example below, we can use the clone() method to create a new object Fruit with the same name and weight as its parent.
class Fruit {
constructor(name, weight) {
this.name = name;
this.weight = weight;
}
clone() {
return new Fruit(this.name, this.weight);
}
}
export default Fruit;
๐ Use this pattern when:
โ Our code should not depend on the concrete classes of objects that you need to copy.
โ We want to reduce the number of subclasses that only differ in how they initialize their respective objects.
๐ Pros:
โ We can clone objects without coupling to their concrete classes.
โ We can eliminate repeated initialization code in favor of cloning pre-built prototypes.
โ We can produce complex objects more conveniently.
โ We get an alternative to inheritance when dealing with configuration presets for complex objects.
โ Cons:
โ Cloning complex objects that have circular references might be very tricky.
I hope you found it useful. Thanks for reading. ๐
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)