- Published on
Prototype pattern
- Authors
- Name
- Khánh
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:
- Initialize the object.
- 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);