Chris
Chris

Reputation: 58222

Is it possible to use Object.assign to clone an object with its methods?

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

Upvotes: 0

Views: 43

Answers (2)

Bergi
Bergi

Reputation: 664650

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);

Upvotes: 1

Chris
Chris

Reputation: 58222

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.

Upvotes: 0

Related Questions