I’m having a little trouble comprehending something I’m reading in a book. I was hoping maybe someone could shed a little light on it for me. The issue deals with constructor chaining. The book is JavaScript the Definite Guide and its page 170 for anyone that owns the book.
Suppose you have a class A, that you would like to subclass to a class named B. The book suggests a way of making inheritance and constructor chaining easier by doing the following…
B.prototype.superclass = A;
Then within the definition of B…
function B(x,y) {
this.superclass(x);
this.y = y;
}
But the book than goes on to explain that you can only use this trick once. If you were to create a class C that subclasses B and uses this trick again, “then when you create an instance of C, this superclass will refer to B(),and the B() constructor will recurse infinitely.”
Basically I’m not seeing why the B() constructor recurses infinitely. I’ve tested it out and can see by example that the statement above is true, however, I’m still not understanding why.
Thanks for posting. Interesting read, and a better way to do it.
I think I may have also figured out my own question. Here’s what I’m thinking, maybe you can confirm if my reasoning makes sense…
So suppose we have the following…
function A(x) {
this.x = x;
}
B.prototype.superclass = A;
function B(x,y) {
this.superclass(x);
this.y = y;
}
C.prototype.superclass = B;
function C(x,y,z) {
this.superclass(x,y);
this.z = z;
}
So what I’m thinking is that since we are calling this.superclass(x,y) from within the body of function C as a method of ‘this’, that when we do this the ‘this’ variable within B will still be referring to the new instance of C, and so this.superclass actually refers to B() again and not A(), and so B() is just called over and over.
Man, I hope that’s right because otherwise I really have no idea. Ha.