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)
}
We use the extends keyword to implement the inheritance in ES6. The class to be extended is called a base class or parent class.
Subclassing is a term that refers to inheriting properties for a new object from a base or superclass object. In traditional object-oriented programming, a class B is able to extend another class A . Here we consider A a superclass and B a subclass of A . As such, all instances of B inherit the methods from A .
We can see that the extends keyword takes care of extending the parent class Animal to the subclass in ES6 way, but the super keyword is also used here to make sure that Animal class is called via Gorilla 's constructor so as to inherit the characteristics and behaviors of the Animal .
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With