DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Creational - Prototype

Image description

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;
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ 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:

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, weโ€™ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, weโ€™ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more