我正在尝试覆盖父类中的一个方法,但存在一些问题。
下面是我正在尝试的场景的代码片段。
class Parent {
add = () => {
console.log('Parent method');
}
}
class Child extends Parent {
add () {
console.log('Child Method');
}
}
// Creating an instance
const child = new Child();
child.add();
它正在调用 Parent 方法添加,因为它是箭头函数,有人可以解释为什么会这样。如果我使父函数成为一个简单的 javascript 方法,那么子函数就可以覆盖。
其他详细信息:
- 我无权访问 Parent,因为它是图书馆的一部分。
- 我不能让我的子类方法作为实例属性(箭头函数) , 存在的原因还有 为 child ( child 的 child )编写的规范,如果我们使用箭头 我们将无法调用 super 函数。
- 不能重命名子函数名称。
最佳答案
这是 one of few reasons why arrow methods aren't convenient .它们限制了扩展和测试类的方式。
Class fields (哪些箭头方法是)是构造函数代码的语法糖:
class Parent {
constructor() {
this.add = () => {...};
}
}
只有另一个箭头方法可以覆盖父箭头方法,因为它们是在类构造函数中定义的,而不是在类原型(prototype)上:
class Child extends Parent {
add = () => {
/* no super.add here because add is not prototype method */
}
}
如果要使用 super.add
,解决方法是存储父方法:
class Child extends Parent {
superAdd = this.add;
add = () => {
this.superAdd();
}
}
请注意,由于这是构造函数代码的语法糖,因此 superAdd
和 add
的定义顺序很重要。
关于Javascript子类方法不覆盖父类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51400605/