【问题标题】:Cloning extended objects in Javascript, keeping all father's methods [duplicate]在Javascript中克隆扩展对象,保留所有父亲的方法[重复]
【发布时间】:2020-04-22 06:56:37
【问题描述】:

我无法在 JS 中实现一个完整且令人满意的克隆方法。 我有这个父类,有属性和方法,当然每个派生类都要访问这个父类的方法

class Father {
    constructor() {
        this.fatherProp = 1;
    }

    fatherMethod() {
        console.log('father method');
    }
}

还有这个子类,它扩展了前一个

class Child extends Father {
    constructor() {
        super();
        this.childProp = 2;
    }
}

客户端代码运行良好

let child1 = new Child();
console.log(child1); // CONSOLE: Child {fatherProp: 1, childProp: 2}
child1.fatherMethod(); // CONSOLE: father method

然后,我需要克隆子对象,当然要保持所有相同的父/子类结构、属性和方法。所以我在Father类中添加了一个clone方法

class Father {
    constructor() {
        this.fatherProp = 1;
    }

    fatherMethod() {
        console.log('father method');
    }

    clone() {
        let newObject = {};
        Object.assign(newObject, this);
        return newObject;
    }
}

客户端代码可以正常工作。

let child2 = child1.clone();
console.log(child2); // CONSOLE: {fatherProp: 1, childProp: 2} *** "Child" type missing
child2.fatherMethod(); // CONSOLE: Uncaught TypeError: child2.fatherMethod is not a function

深入记录两个对象,我可以看到第一个孩子(图片中的蓝色)将“父亲”作为“__proto”。而第二个对象(红色)有空的 __proto

发生了什么事? 在这种情况下我应该如何克隆一个对象? 谢谢

【问题讨论】:

  • 这就是newObject = {} 创建的。你需要创建你的类的一个实例。

标签: javascript ecmascript-6 clone es6-class


【解决方案1】:

您的克隆方法返回一个对象而不是一个类,一种方式:

class Father {
    constructor() {
        this.fatherProp = 1;
    }

    fatherMethod() {
        console.log('father method');
    }

    clone() {
        let clone = Object.assign( Object.create( Object.getPrototypeOf(this)), this);
        return clone;
    }
}

class Child extends Father {
    constructor() {
        super();
        this.childProp = 2;
    }
}


let child1 = new Child();
console.log(child1); // CONSOLE: Child {fatherProp: 1, childProp: 2}
child1.fatherMethod(); // CONSOLE: father method

let child2 = child1.clone();
console.log(child2); // CONSOLE: {fatherProp: 1, childProp: 2} *** "Child" type missing
child2.fatherMethod(); // CONSOLE: Uncaught TypeError: child2.fatherMethod is not a function

【讨论】:

  • 它工作,感谢大家。 (这实际上是一个重复的问题。)
猜你喜欢
  • 2014-01-11
  • 2014-07-08
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
相关资源
最近更新 更多