最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Override parent method with child method - Stack Overflow

programmeradmin1浏览0评论

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 ?

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 ?

Share Improve this question edited Mar 21, 2017 at 11:50 Fatas asked Mar 21, 2017 at 9:10 FatasFatas 2951 gold badge4 silver badges16 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 25

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

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

发布评论

评论列表(0)

  1. 暂无评论