Fatas
Fatas

Reputation: 295

Javascript Override parent method with child method

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 ?

Upvotes: 11

Views: 26087

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68645

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

Upvotes: 25

Joshua Duxbury
Joshua Duxbury

Reputation: 5260

You can create new instances or return functions to make them accessible

var Parent = function(){
       return () => {
          alert("parent");
       };
  };

  var Child = function(){
      this.myMethod = function(){
        alert("child")
         Parent()();
      }
  };
var foo = new Child();
foo.myMethod();

jsfiddle example

Upvotes: -2

Related Questions