How do I override inherited methods when using JavaScript ES6/ES2015 subclassing

后端 未结 1 944
迷失自我
迷失自我 2021-02-06 23:02

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

1条回答
  •  礼貌的吻别
    2021-02-06 23:55

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

    0 讨论(0)
提交回复
热议问题