0

I want to use Object.assign to clone an instance of a class, including any methods along with it. Is it possible to do with just Object.assign or should I be using something like lodash deepClone?

class Foo {
  constructor() {
    this.a = 1; 
    this.b = 2;
  }

  add() {
    return this.a + this.b;
  }
}


const foo1 = new Foo();
console.log(foo1.add());
console.log(foo1.b);


// ? Where did the add go?
const foo2 = Object.assign({}, foo1, { b: 99 });
console.log(foo2.add());
console.log(foo2.b);

Example - http://jsbin.com/dacopazanu/edit?js,console

Chris
  • 54,599
  • 30
  • 149
  • 186
  • 2
    From the [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign), The `Object.assign()` method only copies enumerable and own properties from a source object to a target object. And I am unable to find that `add()` is an enumerable or properties. Why don't you just instantiate another `new Foo()` on `foo2` and assign its' `b` to `99`? – choz May 02 '16 at 10:22

2 Answers2

1

Object.assign only copies own enumerable properties, which inherited class methods are not.

But you wouldn't want to copy those anyway - to clone an instance, you want to create an object that inherits from the same prototype:

const foo2 = Object.assign(Object.create(Object.getPrototypeOf(foo1)), foo1);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

It appears the answer is, that out of the box, no it's not possible.

Using helpful utility libraries like lodash and in particular it's cloneDeep method seems to be the sure way to go.

Chris
  • 54,599
  • 30
  • 149
  • 186