1

I have the following parent class...

function Parent(id, name, parameters) {
  Object.defineProperty(this, "id", {
    value: id
  });

  Object.defineProperty(this, "name", {
    value: name,
    writable: true
  });
};

and the corresponding child class:

function Child(id, name, parameters) {
  Object.defineProperty(this, "phone", {
    value: parameters.phone,
    writable: true
  });
};

I tried to apply inheritance by adding something like Child.prototype = Object.create(Parent.prototype); , but this obviously does not work.

How can I inherit from the Parent class such that I can use the properties id and name.

fyaa
  • 646
  • 1
  • 7
  • 25
  • 1
    I suggest you read my answer here. That might help you a bit to understand how inheritance can be achieved in the prototype way. http://stackoverflow.com/questions/28600238/trying-to-understand-the-difference-between-prototype-and-constructor-in-javascr/28600866#28600866 – Tschallacka Mar 03 '15 at 14:36
  • The solution in this post helped me a lot, I just changed Child.prototype = new Parent(); to Child.prototype = Object.create(Parent.prototype); – fyaa Mar 03 '15 at 15:06

1 Answers1

3

I tried to apply inheritance by adding something like Child.prototype = Object.create(Parent.prototype);

Yes, you should do that, to create a prototype chain between your .prototype objects. You have your methods defined on them, don't you?

How can I inherit from the Parent class such that I can use the properties id and name.

You basically need a "super" call to the Parent constructor so that it sets up your properties on Child instances:

function Child(id, name, parameters) {
  Parent.call(this, id, name, parameters);
  Object.defineProperty(this, "phone", {
    value: parameters.phone,
    writable: true
  });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thank you, actually I could already read it out Michael Dibbet's post. Besides this Parent.call I had to define the following after the function declaration: Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; – fyaa Mar 03 '15 at 15:04