Search code examples
javascriptcloning

How to copy object methods in ES6


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]

Solution

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