How to clone a javascript ES6 class instance

前端 未结 7 2027
猫巷女王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:45

    class A {
      constructor() {
        this.x = 1;
      }
    
      y() {
        return 1;
      }
    }
    
    const a = new A();
    
    const output = Object.getOwnPropertyNames(Object.getPrototypeOf(a)).concat(Object.getOwnPropertyNames(a)).reduce((accumulator, currentValue, currentIndex, array) => {
      accumulator[currentValue] = a[currentValue];
      return accumulator;
    }, {});
    

提交回复
热议问题