使用JavaScript ES6 / ES2015子类化时,如何覆盖继承的方法 [英] How do I override inherited methods when using JavaScript ES6/ES2015 subclassing

查看:752
本文介绍了使用JavaScript ES6 / ES2015子类化时,如何覆盖继承的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个扩展Array的类。我想在调用继承的push函数之前执行任意代码。

I have created a class that extends Array. I want to execute arbitrary code before calling the inherited push function.

class newArray extends Array{
      //execute any logic require before pushing value onto array
      this.push(value)    
}

推荐答案

我找到的解决方案是在子类中创建一个与继承函数同名的新函数。在这种情况下推。然后在覆盖函数内部通过super关键字调用继承的函数。

The solution I found was to create a new function in the subclass that has the same name as the inherited function. In this case push. Then inside the overriding function the inherited function is called via the super keyword.

class newArray extends Array{
    push(value) {
      //execute any logic require before pushing value onto array
      console.log(`pushed ${value} on to array`)
      super.push(value)}    
}

var array = new newArray

array.push('new Value')

这篇关于使用JavaScript ES6 / ES2015子类化时,如何覆盖继承的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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