使用JavaScript ES6 / ES2015子类化时,如何覆盖继承的方法

问题描述 投票:19回答:1

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

class newArray extends Array{
      //execute any logic require before pushing value onto array
      this.push(value)    
}
class inheritance ecmascript-6 override subclass
1个回答
40
投票

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

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')
© www.soinside.com 2019 - 2024. All rights reserved.