+1
Fixed

The typescript example of Prototype seems to have incorrect code

Himanshu 3 years ago updated by Alexander 2 weeks ago 2

https://refactoring.guru/design-patterns/prototype/typescript/example

In the clone method of Prototype, we have the following line

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

It seems to be wrong, as this is referencing a completely different temporary object. 

I think the correct code is

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

Please correct me if I am wrong. Thank you

Answer

Answer
Fixed

Thank you for reporting this. I've fixed the error and I'm uploading the fix right now.

Hi there, I think the `clone()` function needs to be updated.

public clone(): this {

// 1) Create a new empty object with the same prototype as `this`

const clone = Object.create(Object.getPrototypeOf(this) as this;

// 2) all descriptors (enumerable + non-enumerable + symbol) - just in case

const descriptors = Object.getOwnPropertyDescriptors(this);

// 3) Copy all descriptors

Object.defineProperties(clone, descriptors);

// 4) Same approach for the component

const compClone = Object.create(Object.getPrototypeOf(this.component));

const compDescriptors = Object.getOwnPropertyDescriptors(this.component);

Object.defineProperties(compClone, compDescriptors);

clone.component = compClone;

// 5) Recreate the back-reference so it points to the clone, not the original

clone.circularReference = new ComponentWithBackReference(clone);

return clone;

}

Answer
Fixed

Thank you for reporting this. I've fixed the error and I'm uploading the fix right now.