Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Override parent method with child method

Tags:

javascript

How i can override parent method on child ? Is javascript have something like parent::method();

var Parent = function(){
       this.myMethod(){
          //Some code here
       };
    }

    var Child = function(){
       Parent.call(this);
       this.myMethod(){
          //Some code here
          //and then run parent method
       };
    }

Updated There is better way than do that (not ES6)?:

var Parent = function ()
{
    this.myMethod()
    {
        this.extedMyMethod()
        //Some code here
    };

    this.extedMyMethod()

}

var Child = function ()
{
    Parent.call(this);
    this.extedMyMethod()
    {
        //Some code which expand parent method
    };
}

P.S. If i do like @Suren Srapyan suguest webpack will convert to proper non ES6 ?

like image 415
Fatas Avatar asked Mar 21 '17 09:03

Fatas


People also ask

Can you override methods in JavaScript?

To override a method, we give it the same name and parameters as the method in the superclass. We can override receiveDamage() from the superclass by coding the same method in the subclass.

How to override constructor in JavaScript?

Otherwise, use a simple structure with methods declared with prototype, you can get a better performance. var MyObject = (function () { // Constructor function MyObject (foo) { this. _foo = foo; } function privateFun (prefix) { return prefix + this. _foo; } MyObject.

Which of the following keywords is used to override the parent class methods in js?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.

How do you use parent method in JavaScript?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.


1 Answers

With ES6 class syntax inheritance you can do it via super calls.

class Parent{
   method(){
    console.log('Parent !!!');
   }
}

class Child extends Parent{
  
  constructor(){
     super();
  }

   method(){
    console.log('Child !!!');
    super.method();
   }
}

var child = new Child();
child.method();

UPDATED

You need also to use polyfill for different browsers

like image 117
Suren Srapyan Avatar answered Oct 21 '22 16:10

Suren Srapyan