Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)    
}
like image 408
Udesh Avatar asked Oct 06 '16 03:10

Udesh


People also ask

Which keyword can be used to implement inheritance in ES6?

We use the extends keyword to implement the inheritance in ES6. The class to be extended is called a base class or parent class.

What is Subclassing in Javascript?

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 .

What is the work of super and extends keyword?

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 .


1 Answers

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')
like image 132
Udesh Avatar answered Oct 18 '22 21:10

Udesh