I have this snippet of JavaScript code:
class Foo {
constructor() {
this.b = 1;
this.getB = () => { return this.b; };
}
}
const normalFoo = new Foo();
const clonedFoo = magicClone(normalFoo);
clonedFoo.b = 5;
console.log(clonedFoo instanceof Foo); // should be true
console.log(clonedFoo.getB()); // should be 5
I'd like to know what I can replace magicClone
with in order to get the desired result (e.g. a clone that respects arrow function binding).
I'm fine with any sorts of terrible hacks and I'm also fine with solutions that work most of the time, as long as they work in this case. This is mostly for my edification :)
Please don't close this question as a duplicate - cloning an object has been asked many times, but I couldn't find a single answer that does this. Object.assign
, lodash's cloneDeep
, jQuery's clone, etc all do not handle this case.