|
| 1 | +export {}; |
| 2 | + |
| 3 | +class Prototype { |
| 4 | + public primitive: any; |
| 5 | + public component: object; |
| 6 | + public circularReference: ComponentWithBackReference; |
| 7 | + |
| 8 | + public clone(): this { |
| 9 | + const clone = Object.create(this); |
| 10 | + |
| 11 | + clone.component = Object.create(this.component); |
| 12 | + |
| 13 | + clone.circularReference = { |
| 14 | + ...this.circularReference, |
| 15 | + prototype: { ...this }, |
| 16 | + }; |
| 17 | + |
| 18 | + return clone; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +class ComponentWithBackReference { |
| 23 | + public prototype; |
| 24 | + |
| 25 | + constructor(prototype: Prototype) { |
| 26 | + this.prototype = prototype; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +function clientCode() { |
| 31 | + const p1 = new Prototype(); |
| 32 | + p1.primitive = 245; |
| 33 | + p1.component = new Date(); |
| 34 | + p1.circularReference = new ComponentWithBackReference(p1); |
| 35 | + |
| 36 | + const p2 = p1.clone(); |
| 37 | + if (p1.primitive === p2.primitive) { |
| 38 | + console.log('Primitive field values have been carried over to a clone. Yay!'); |
| 39 | + } else { |
| 40 | + console.log('Primitive field values have not been copied. Booo!'); |
| 41 | + } |
| 42 | + if (p1.component === p2.component) { |
| 43 | + console.log('Simple componet has not been cloned. Booo!'); |
| 44 | + } else { |
| 45 | + console.log('Simple component has been cloned. Yay!'); |
| 46 | + } |
| 47 | + |
| 48 | + if (p1.circularReference === p2.circularReference) { |
| 49 | + console.log('Component with back reference has not been cloned. Booo!'); |
| 50 | + } else { |
| 51 | + console.log('Component with back refarence has been cloned. Yay!'); |
| 52 | + } |
| 53 | + if (p1.circularReference.prototype === p2.circularReference.prototype) { |
| 54 | + console.log('Component with back reference is linked to original object. Booo!'); |
| 55 | + } else { |
| 56 | + console.log('Component with back reference is linked to the clone. Yay!'); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +clientCode(); |
0 commit comments