Overview
I have the JavaScript classes Parent, Child1, and Child2. Both children extend Parent. I want to write a method that "semi-deep" copies (explained later) the object. Because in actuallity there could be hundreds of children, I'd write this method on the parent and all children inherit that method. But the copy always returns the type that called it.
For instance, the usage would be the following:
const parent = new Parent([1, 2, 3])
const parentCopy = parent.copy() // parentCopy has type Parent
const child1 = new Child1([1, 2, 3])
const child1Copy = child1.copy() // child1Copy has type Child1
const child2 = new Child2([1, 2, 3])
const child2Copy = child2.copy() // child2Copy has type Child2
How can I do this?
What I've tried
If this were not a class, you could use destructuring:
const copy = {...original}
This is the same affect I want. However, since this is a class, I assume I'll need to eventually create a new Thing
. For instance, here's how I could create a copy of Parent
.
class Parent {
// ...
copy() {
return new Parent()
}
}
However, this solution means I'd need to override it for every single child. How can I say instead to create a new WhateverThisTypeActuallyis
? So if this is a Child1 calling the copy, it'll create a new Child1()
.
What does "semi-deep" mean?
Briefly, a shallow copy is just a reference to the actual object. For instance, the following code snippet performs a shallow copy.
let object = { a: 2, b: 3 };
let copy = object;
object.a = 5;
console.log(copy.a);
This is not what I want. I want to create a new version of the object. However, I do want to shallow copy any properties the object may have. So I don't need a structured clone which does a recursive deep copy.
Other requirements
This should be pure JavaScript. I cannot use other dependencies or npm packages.