0

I am trying to clone an object created with new. The only way I found to do it is:

let tmp = Object.create(instance.__proto__);
let obj = Object.assign(tmp, instance);

This examples works and does the job, but doesn't look like a proper solution. I was wondering if there is a better way to clone the object created with new?

Any help will be appreciated!

andrey
  • 1,867
  • 3
  • 21
  • 34
  • 1
    The question marked as duplicate is talking about jQuery, but there is an answer without jQuery that might help https://stackoverflow.com/a/43753414/340760 – BrunoLM Feb 11 '18 at 22:16
  • 1
    Yeah, most of the answers there either don't rely on jQuery at all or just use `$.extend`, which was a precursor to `Object.assign` (one of several). – T.J. Crowder Feb 11 '18 at 22:20

1 Answers1

0

It all depends if you want to make a deep or shallow clone.

For the simplicity let's assume that you want to create a shallow clone as in your code.

Then, you can either use shorter version of the code you provided:

let obj = Object.assign({}, instance);

Or use ES6 spread syntax:

let obj = {...instance};

Both ways are correct.

pwolaq
  • 6,343
  • 19
  • 45
  • 2
    thanks for answer, i think this way you will not have prototype cloned.. – andrey Feb 11 '18 at 22:16
  • 1
    @BrunoLM: No, nothing in the above will assign `instance`'s prototype to `obj`, nor copy inherited properties from `instance` to `obj`. (You're correct, though, that if an own property refers to an object, both objects will refer to the same target object. That's what pwolaq means by "shallow.") – T.J. Crowder Feb 11 '18 at 22:25