Anton Putau
Anton Putau

Reputation: 762

Call parent prototype from child prototype

My parent class is

   function Parent() {}

   Parent.prototype.get = function() {}

   Parent.prototype.start= function() {  this._start() }

My child is

   function Child(){ Parent.call(this, arguments) }

   Child.prototype._start = function(){   this.get() /* error here - this.get is not a function*/ }  

   util.inherits(Child, Parent);

When I do

    new Child().start()

I got an error this.get is not a function. How can I call parent prototype function? Thanks.

Upvotes: 1

Views: 731

Answers (1)

adeneo
adeneo

Reputation: 318182

As the use of util.inherits is discouraged, you should use extends for classes, but you seem to have just regular functions, which means you can set the prototype of the child to the same as the parent before starting to extend it further

function Parent() {}

Parent.prototype.get = function() {
  console.log('works fine');
}

Parent.prototype.start = function() {
  this._start();
}


function Child() {
  Parent.call(this, arguments);
}

Child.prototype = Parent.prototype;

Child.prototype._start = function() {
  this.get();
}


var instance = new Child();

instance.start();

Note that Parent and Child now have the same prototype, so by changing one, you'd be changing the other as well.
If for some reason you have to avoid that, using Object.create (or assign) would do that

Child.prototype = Object.create(Parent.prototype);

Upvotes: 3

Related Questions