我有类似于以下父类和子类的代码:
const modify = (data) => {
const newData = data
// changes newData in some way
return newData
}
class Parent {
constructor(data) {
this.data = data
}
modify() {
return new Parent(modify(this.data))
}
}
class Child extends parent {
constructor(data) {
super(data)
}
}
是否有办法更改 Parent 类的
modify
函数,以在使用 Child 实例调用时返回 Child 实例?
我知道在静态函数中,您可以使用
new this()
来做到这一点,方法是否有等效的东西?或者我是否必须覆盖 Child 类中的 Parent 方法?
我只需编写
Parent
和 Child
的方法调用,以确保创建正确的实例。
由于
modify
函数正在完成所有工作,因此在 modify
和 Parent
上定义 Child
并不难。
const main = () => {
console.log('=== Parent ===');
let parent = new Parent({ timestamp: Date.now() });
console.log(parent);
parent = parent.modify({ timestamp: Date.now(), updated: true });
console.log(parent);
console.log(parent.constructor.name); // Parent
console.log('=== Child ===');
let child = new Child({ timestamp: Date.now() });
console.log(child);
child = child.modify({ timestamp: Date.now(), updated: true });
console.log(child);
console.log(child.constructor.name); // Child
};
// Naive merge function
const modify = (source, update) => ({ ...source, ...update });
class Parent {
constructor(data) {
this.data = data
}
modify(update) {
return new Parent(modify(this.data, update));
}
}
class Child extends Parent {
constructor(data) {
super(data)
}
modify(update) {
return new Child(modify(this.data, update));
}
}
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }