I have not been able to find an answer to this. Objects in JavaScript have an inheritance chain; the chain of any function is Function => Object
, the chain of an instance of TypeError
is TypeError => Error => Object
, and the chain of TypeError
is, oddly, Function => Function => Object
.
I had looked up how to make a constructed object inherit properties from another function in addition to its direct constructor, expecting the resulting inheritance chain to be object => constructor => second function
and for this to be how one constructor would extend another. The solution that I had found was to call <second function>.<call or apply>(this[, optional arguments...])
inside the body of the constructor, but object instanceof <second function>
ended up returning false
.
Further research revealed mostly answers that use class syntax or Object.create
, but those are new and one "class" extending another in JavaScript has been around since the creation of the language, so there's some other way that's used to do this. This information is something that should be mentioned right alongside basic explanations of JavaScript constructors yet it is not. What is the primary method of extending a "class" (not actual class syntax) resulting in deeper inheritance chains?
Example result:
// Square is the subclass
// Rectangle is the superclass
var rectangle = new Rectangle(1, 1);
var square = new Square(1);
rectangle instanceof Rectangle; // true
rectangle instanceof Square; // false
square instanceof Rectangle; // true
square instanceof Square; // true
Square instanceof Rectangle; // true
False solution:
function F () {
this.value = 0;
}
function G () {
F.apply(this);
}
var f = new F();
var g = new G();
// g gets the same properties from F that f gets.
"value" in f; // true
"value" in g; // true
// But neither g nor G are instances of F.
g instanceof G; // true
g instanceof F; // false
G instanceof F; // false