How to extend a class in JavaScript, when it has no default constructor?

Refresh

April 2019

Views

26 time

0

In JavaScript, how do I extend a base class, when there is no constructor suitable to use when assigning the prototype of the new class? Solution...

  1. Must pass instanceof test.
  2. Must not modify existing constructor.
  3. Must call super constructor.
  4. Must not include an intermediate class I write.
  5. Must not have dependency on third party code, like jQuery.
  6. May involve a helper function you provide.

Here is what I've tried.

function Person(name) { // Immutable base class.
  if (typeof name != "string" || name == "") {
    throw new Error("A person must have a valid name.");
  }
  this.getName = function() {
    return name;
  }
}

function Artist(name) { // My extending class.
  Person.call(this, name); // Call super constructor.
}
Artist.prototype = new Person(); // Express inheritance without parameters.
var tom = new Artist("Tom");
console.info(tom instanceof Person); // Must print true.
console.info(tom.getName()); // Must print Tom.

My solution fails because an exception is thrown

1 answers

1

You're doing inheritance wrong, it should be:

Artist.prototype = Object.create(Person.prototype);

That works and all your tests are passed.

Useful reading: Inheritance in JavaScript