0

I wish to be able to clone objects of my class. How should I implement the clone method for the class below?

export default class Foo {
    constructor(data) {
        this.name = data.firstName + " " + data.lastName 
        this.id = data.objectId
    }

    clone(s){
    }
}

2 Answers 2

1

Just create another instance of the class and copy over the properties:

clone() {
    return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
//  or simply
//  return Object.assign(new this.constructor({}), this);
}

You might also pass the options so that the properties are initialised in the constructor as expected:

clone() {
    return new Foo({
        firstName: this.name.split(" ")[0],
        lastName: this.name.split(" ").slice(1).join(" "),
        objectId: this.id
    });
}

However, notice that creating multiple instances with the same (but supposedly unique) id might not be the best idea.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you want to clone from one instance of a class to another, you can use Object.assign:

export default class Foo {
    constructor(data) {
        this.name = data.firstName + " " + data.lastName 
        this.id = data.objectId
    }

    clone(s) {
      // It's important to initalize using an empty object, so as to not cause errors
      let copy = new Foo({});
      Object.assign(copy, this);
      return copy;
    }
}

2 Comments

Keep in mind this will fail dangerously if you happen to bind any methods in the class constructor since the bound methods would also be copied.
If you wanted to play it safe, could you for through the elements of this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.