Contact Me

Prototype

 This pattern allows you to create new objects by copying existing objects, rather than creating new objects from scratch. This can be useful when you want to create a new object that is similar to an existing object, but with some differences, and when you want to avoid the overhead of creating new objects from scratch.


Here is an example of the prototype pattern in JavaScript:


class Prototype {

constructor(name) {

  this.name = name;

}

clone() {

  return Object.create(this);

}

}

const prototype1 = new Prototype('Prototype 1');

const prototype2 = new Prototype('Prototype 2');

const clone1 = prototype1.clone();

const clone2 = prototype2.clone();

console.log(clone1.name);

// Output: 'Prototype 1'

console.log(clone2.name);

// Output: 'Prototype 2'


In this example, the Prototype class is a class that represents an object that can be cloned, and the clone() method is a method that creates a new object by copying the existing object. To use the prototype pattern, we create instances of the Prototype class, and then call the clone() method on these instances to create new objects that are copies of the original objects.

The prototype pattern is often implemented using the Object.create() method, which creates a new object with a specified prototype object and properties. In the example above, the clone() method uses the Object.create() method to create a new object with the same prototype as the original object, and returns this new object.