How to clone a javascript ES6 class instance

前端 未结 7 2028
猫巷女王i
猫巷女王i 2020-12-02 10:48

How do I clone a Javascript class instance using ES6.

I\'m not interested in solutions based on jquery or $extend.

I\'ve seen quite old discussions of object

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 11:42

    I like almost all the answers. I had this problem and to resolve it I would do it manually by defining a clone() method and inside it, I would build the whole object from scratch. For me, this makes sense because the resulted object will be naturally of the same type as the cloned object.

    Example with typescript:

    export default class ClassName {
        private name: string;
        private anotherVariable: string;
       
        constructor(name: string, anotherVariable: string) {
            this.name = name;
            this.anotherVariable = anotherVariable;
        }
    
        public clone(): ClassName {
            return new ClassName(this.name, this.anotherVariable);
        }
    }
    

    I like this solution because it looks more 'Object Oriented'y

提交回复
热议问题