Published on

Prototype pattern

Authors
  • avatar
    Name
    Khánh
    Twitter

Prototype

An object needs to be cloned from an existing object. Instead of creating a new object, a clone function can be implemented in the class to easily clone the object.

Steps:

  1. Initialize the object.
  2. Write a clone() function to return a new object.

Examples

class Person {
  constructor(public name: string, public age: number) {}

  //   This function uses to clone new objects
  public clone() {
    return new Person(this.name, this.age);
  }
}

const manager = new Person("manager", 55);
console.log(manager);

const subManager = manager.clone();
subManager.name = "subManager";
console.log(subManager);

console.log(manager === subManager);

References