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...
- Must pass
instanceoftest. - Must not modify existing constructor.
- Must call super constructor.
- Must not include an intermediate class I write.
- Must not have dependency on third party code, like jQuery.
- 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
getNameis flawed right nowclass: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…?