[英]Javascript Child Class method not overriding Parent Class Method
I am trying to override one method from the parent class, but there are some issues. 我正在尝试从父类重写一个方法,但是存在一些问题。
Below is the code snippet of my scenario which I am trying. 下面是我正在尝试的方案的代码片段。
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();
It is calling the Parent method add as that is arrow function, Can someone explain why this is happening. 它正在调用Parent方法add,即箭头功能,有人可以解释为什么会这样。 If I make the parent function a simple javascript method then child is able to override. 如果我将父函数设为简单的javascript方法,则子函数可以覆盖。
Additonal Details : 其他详细信息 :
This is one of few reasons why arrow methods aren't convenient . 这是箭头方法不方便的几个原因之一 。 They limit the ways in which a class can be extended and tested. 它们限制了类的扩展和测试方式。
Class fields (which arrow methods are) are syntactic sugar for constructor code: 类字段 (箭头方法是)是构造函数代码的语法糖:
class Parent {
constructor() {
this.add = () => {...};
}
}
Only another arrow method can override parent arrow method, because they are defined in class constructor, not on class prototype: 只有另一个arrow方法可以覆盖父arrow方法,因为它们是在类构造函数中定义的,而不是在类原型上定义的:
class Child extends Parent {
add = () => {
/* no super.add here because add is not prototype method */
}
}
If super.add
is intended to be used, a workaround is to store parent method: 如果打算使用super.add
,则一种解决方法是存储父方法:
class Child extends Parent {
superAdd = this.add;
add = () => {
this.superAdd();
}
}
Notice that since this is syntactic sugar for constructor code, the order in which superAdd
and add
are defined matters. 注意,由于这是构造函数代码的语法糖,因此定义superAdd
和add
的顺序很重要。
The parent add
is an instance property, and it overshadows the child's class method, which is part of the instance's prototype. 父add
是一个实例属性,它使子类的类方法(该类的实例原型的一部分)黯然失色。 It's a bit hacking, but you can rename and delete the class property in the constructor: 这有点hacking,但是您可以在构造函数中重命名和删除class属性:
class Parent { add = () => { console.log('Parent method'); } } class Child extends Parent { constructor() { super(); this.parentAdd = this.add; delete this.add; } add() { console.log('Child Method'); this.parentAdd(); // if you need call the parent's method } } const child = new Child(); child.add();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.