Baz
Baz

Reputation: 13135

Add method for cloning class objects

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){
    }
}

Upvotes: 0

Views: 222

Answers (2)

Bergi
Bergi

Reputation: 664650

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.

Upvotes: 1

bren
bren

Reputation: 4334

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

Upvotes: 1

Related Questions