Quiz

Explain the concept of the Prototype pattern

Topics
JavaScriptOOP
Edit on GitHub

TL;DR

The Prototype pattern is a creational design pattern used to create new objects by copying an existing object, known as the prototype. This pattern is useful when the cost of creating a new object is more expensive than cloning an existing one. In JavaScript, this can be achieved using the Object.create method or by using the prototype property of a constructor function.

const prototypeObject = {
greet() {
console.log('Hello, world!');
},
};
const newObject = Object.create(prototypeObject);
newObject.greet(); // Outputs: Hello, world!

The Prototype pattern

The Prototype pattern is a creational design pattern that allows you to create new objects by copying an existing object, known as the prototype. This pattern is particularly useful when the cost of creating a new object is more expensive than cloning an existing one.

How it works

In the Prototype pattern, an object is used as a blueprint for creating new objects. This blueprint object is called the prototype. New objects are created by copying the prototype, which can be done in various ways depending on the programming language.

Implementation in JavaScript

In JavaScript, the Prototype pattern can be implemented using the Object.create method or by using the prototype property of a constructor function.

Using Object.create

The Object.create method creates a new object with the specified prototype object and properties.

const prototypeObject = {
greet() {
console.log('Hello, world!');
},
};
const newObject = Object.create(prototypeObject);
newObject.greet(); // Outputs: Hello, world!

In this example, newObject is created with prototypeObject as its prototype. This means that newObject inherits the greet method from prototypeObject.

Using constructor functions and the prototype property

Another way to implement the Prototype pattern in JavaScript is by using constructor functions and the prototype property.

function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
const person2 = new Person('Bob');
person1.greet(); // Outputs: Hello, my name is Alice
person2.greet(); // Outputs: Hello, my name is Bob

In this example, the Person constructor function is used to create new Person objects. The greet method is added to the Person.prototype, so all instances of Person inherit this method.

Advantages

  • Reduces the cost of creating new objects by cloning existing ones
  • Simplifies the creation of complex objects
  • Promotes code reuse and reduces redundancy

Disadvantages

  • Cloning objects can be less efficient than creating new ones in some cases
  • Can lead to issues with deep cloning if the prototype object contains nested objects

Further reading

Edit on GitHub