简体   繁体   English

Javascript子类方法不覆盖父类方法

[英]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 : 其他详细信息

  1. I don't have access to Parent as it is part of library. 我无权访问“父母”,因为它是图书馆的一部分。
  2. I can't make my child class method as instance properties (arrow function) , the reason for being that there are further specification written for child (child of child) and If we use arrow functions we will not be able to call the super. 我不能将我的子类方法用作实例属性(箭头函数),原因是还有针对孩子(孩子的孩子)编写的规范,如果我们使用箭头函数,我们将无法调用父对象。
  3. Child function name can't be renamed. 子函数名称无法重命名。

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. 注意,由于这是构造函数代码的语法糖,因此定义superAddadd的顺序很重要。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM