在Javascript ES6中扩展子类中的父类方法 [英] Extending parent class methods in child class in Javascript ES6

查看:630
本文介绍了在Javascript ES6中扩展子类中的父类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展子类在父类中的特定方法的功能。我仍然习惯于ES6中的OOP,所以我不确定这是否可行或违反规则。

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.

我正在寻找类似这样的东西:

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?

推荐答案

你可以使用<$ c方法中$ c> super :

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

这个在子类和父类中是一样的,并引用实际的对象,所以如果你在父代码中调用一个方法,它会调用child的实施,如​​果它确实是一个孩子。在其他语言中也是如此,例如Python和Ruby。

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. Same works in other languages, for example Python and Ruby.

工作代码:

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>

这篇关于在Javascript ES6中扩展子类中的父类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆