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

时间:2021-08-31 14:44:28

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

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

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

1 个解决方案

#1


27  

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.

我发现的解决方案是在子类中创建一个与继承函数同名的新函数。在这种情况下推。然后在覆盖函数内部通过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')

#1


27  

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.

我发现的解决方案是在子类中创建一个与继承函数同名的新函数。在这种情况下推。然后在覆盖函数内部通过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')