Skip to content

Latest commit

 

History

History
140 lines (98 loc) · 4.88 KB

File metadata and controls

140 lines (98 loc) · 4.88 KB

El patrón Prototipo

Prototype es un patrón de diseño creacional que nos permite copiar objetos existentes sin que el código dependa de sus clases.

El patrón prototipo es una forma útil de compartir propiedades entre muchos objetos del mismo tipo.

En nuestras aplicaciones, a menudo tenemos que crear muchos objetos del mismo tipo. Una forma útil de hacerlo es creando múltiples instancias de una clase ES6.

Usar el patrón Constructor nos brinda ciertas ventajas:

  • Clonar objetos sin acoplarlos: Puedes clonar objetos sin acoplarlos a sus clases concretas.
  • Evitar un código de inicialización repetido: Puedes evitar un código de inicialización repetido clonando prototipos prefabricados.
  • Crear objetos complejos con más facilidad: Puedes crear objetos complejos con más facilidad.
  • Alternativa a la herencia: Puedes obtener una alternativa a la herencia al tratar con preajustes de configuración para objetos complejos.

Object.create

El método Object.create nos permite crear un nuevo objeto, al que podemos pasar explícitamente el valor de un objeto para utilizar su prototipo para la copia.

Podemos añadir nuevas propiedades al objeto creado, o incluso sobrescribir las propiedades del prototipo.

const dog = {
  bark() {
    return `Woof!`;
  }
};



const pet1 = Object.create(dog);

pet1.name = 'Rex';

pet1.bark = function() {
  return `Woof! My name is ${this.name}`;
};

console.log(pet1.name);
console.log(pet1.bark());

Output:

Rex
Woof! My name is Rex

Ejemplo

class Prototype {
  public primitive: any;

  public component: object;

  public circularReference: ComponentWithBackReference;

  public clone(): this {
    const clone = Object.create(this);

    clone.component = Object.create(this.component);

    clone.circularReference = {
      ...this.circularReference,
      prototype: { ...this },
    };

    return clone;
  }
}

class ComponentWithBackReference {
  public prototype;

  constructor(prototype: Prototype) {
    this.prototype = prototype;
  }
}

function clientCode() {
  const prototypeA = new Prototype();

  prototypeA.primitive = 245;
  prototypeA.component = new Date();
  prototypeA.circularReference = new ComponentWithBackReference(prototypeA);

  const prototypeB = prototypeA.clone();

  if (prototypeA.primitive === prototypeB.primitive) {
    console.log('Primitive field values have been carried over to a clone. Yay!');
  } else {
    console.log('Primitive field values have not been copied. Booo!');
  }

  if (prototypeA.component === prototypeB.component) {
    console.log('Simple component has not been cloned. Booo!');
  } else {
    console.log('Simple component has been cloned. Yay!');
  }

  if (prototypeA.circularReference === prototypeB.circularReference) {
    console.log('Component with back reference has not been cloned. Booo!');
  } else {
    console.log('Component with back reference has been cloned. Yay!');
  }

  if (prototypeA.circularReference.prototype === prototypeB.circularReference.prototype) {
    console.log('Component with back reference is linked to original object. Booo!');
  } else {
    console.log('Component with back reference is linked to the clone. Yay!');
  }
}

clientCode();

Output:

Primitive field values have been carried over to a clone. Yay!
Simple component has been cloned. Yay!
Component with back reference has been cloned. Yay!
Component with back reference is linked to the clone. Yay!

Ejemplo en vivo

Ejemplo en vivo

Ver un ejemplo de código

Example