Question Regarding Constructor Chaining and Infinite Recursion

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.

Any insight would be great!

Yep, spot on. it’s the context of the this keyword that’s causing the problem.

With that Object.create function from Crockford, you’ll be all set.

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.

I cannot provide much insight at the moment in regards to why the problem occurs, but I can help you by providing a better way to do things.

Douglas Crockford has some material regarding prototypal javascript which includes a way to properly create new objects.

How does the following grab you?


if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);