Search code examples
javascriptinheritancedefineproperty

Javascript inheritance of properties defined with Object.defineProperty


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.


Solution

  • 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
      });
    }