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

2

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.