【发布时间】: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