How do I override inherited methods when using Jav

2020-05-30 01:27发布

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)    
}

1条回答
Emotional °昔
2楼-- · 2020-05-30 02:17

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')

查看更多
登录 后发表回答