简体   繁体   English

在Javascript ES6中扩展子类中的父类方法

[英]Extending parent class methods in child class in Javascript ES6

I want to extend a child's functionality of a specific method in a parent class. 我想扩展子类在父类中的特定方法的功能。 I'm still getting used to OOP in ES6 so I'm not sure if this is possible or breaks rules. 我仍然习惯于ES6中的OOP,所以我不确定这是否可行或违反规则。

I'm looking for something like this: 我在寻找这样的东西:

class Parent {
  constructor(elem) {
    this.elem = elem;

    elem.addEventListener((e) => {
      this.doSomething(e);
    });
  }

  doSomething(e) {
    console.log('doing something', e);
  }
}

class Child extends Parent {
  constructor(elem) {
    // sets up this.elem, event listener, and initial definition of doSomething
    super(elem)
  }

  doSomething(e) {
    // first does console.log('doing something', e);
    console.log('doing another something', e);
  }
}

In essence I want to append a child-specific callback on a parent method. 本质上,我想在父方法上附加一个特定于子的回调。 Is there a creative way of doing this without creating a completely new class with the same functionality? 有没有一种创造性的方法来创建一个具有相同功能的全新类?

You can use super in methods: 你可以使用super in方法:

doSomething(e) {
  super.doSomething(e)
  console.log('doing another something', e)
}

this in child class and in parent class is the same thing, and refers to the actual object, so if you call a method in parent's code, it will call child's implementation, if it is indeed a child. this在子类和父类中是相同的,并引用实际的对象,所以如果你在父代码中调用一个方法,它将调用child的实现,如果它确实是一个孩子。 Same works in other languages, for example Python and Ruby. 在其他语言中也是如此,例如Python和Ruby。

Working code: 工作代码:

 class Parent { constructor(elem) { this.elem = elem this.elem.addEventListener('click', (e) => { this.doSomething(e) }) } doSomething(e) { alert('doing something') } } class Child extends Parent { constructor(elem) { super(elem) } doSomething(e) { super.doSomething(e) alert('doing another something') } } let child = new Child(document.getElementById('button')) 
 <button id="button">Alert</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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