我无法在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
然后,我需要克隆子对象,当然要保留所有相同的父/子类的结构,属性和方法。所以我在父亲类中添加了一个克隆方法
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
发生了什么事?在这种情况下,应该如何克隆对象?谢谢
您的克隆方法以一种方式返回对象而不是类:
class Father {
constructor() {
this.fatherProp = 1;
}
fatherMethod() {
console.log('father method');
}
clone() {
//let newObject = {};
//Object.assign(newObject, this);
return this;
}
}
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