3

I want to clone an object using the spread operator. However, the methods are not copied as shown

I am aware you could do Object.Assign() but I am looking for a way to do that using ES6 syntax

The solution at Deep copy in ES6 using the spread syntax concerns deep cloning: I am only interested in copying methods as well as properties

The solution at How to clone a javascript ES6 class instance makes use of Object.Assign()

class Test {
  toString() {
    return "This is a test object";
  }
}

let test = new Test();
let test2 = { ...test };

console.log(String(test));
console.log(String(test2));
// Output: This is a test object
// Output: [object Object]
  • use `Object.create` instead of spread. `String(Object.create(test))` works as you want. – rlemon Jul 07 '19 at 13:53
  • Possible duplicate of [How to clone a javascript ES6 class instance](https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance) – Abdelrahman Hossam Jul 07 '19 at 13:57
  • Possible duplicate of [Deep copy in ES6 using the spread syntax](https://stackoverflow.com/questions/38416020/deep-copy-in-es6-using-the-spread-syntax) – Ahmet Zeybek Jul 07 '19 at 13:59
  • I would like to pint out that `Object.assign` **was added** as part of ES6. Thus it is kinda the thing you are looking for... – Akxe Jul 07 '19 at 14:01
  • There is no built-in function in ES6 for this, you should use `cloneDeep()` method in `lodash` – Ahmet Zeybek Jul 07 '19 at 14:01

2 Answers2

2

This:

class Test {
  toString() {
    return "This is a test object";
  }
} 

does not define any object method strictly speaking. It rather defines class methods.

You need to attach methods directly to the object as "own properties" in order the spread to copy them:

class Test {
  constructor() {
    // define toString as a method attached directly to
    // the object
    this.toString = function() {
      return "This is a test object";
    }
  }
}

let test = new Test();
let test2 = { ...test };

console.log(String(test));
console.log(String(test2));
c-smile
  • 26,734
  • 7
  • 59
  • 86
1

I think you can do it like this:

class Test {
  toString() {
    return "This is a test object";
  }
}

let test = new Test();
let test2 = {};

test2.__proto__ = test.__proto__;

console.log(String(test));
console.log(String(test2));

But I dont know, maybe its a bad practice :/..

dan-maximov
  • 31
  • 1
  • 7