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


April 2019


26 time


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., name); // Call super constructor.
Artist.prototype = new Person(); // Express inheritance without parameters.
var tom = new Artist("Tom"); instanceof Person); // Must print true.; // Must print Tom.

My solution fails because an exception is thrown

1 answers


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