On Mar 24, 4:54 pm, Luke <kickingje...@gmail.com> wrote:
> It's late, but I have to ask something though that it still don't
> understand. Why *doesn't* prototype just add a reference to the parent-class
> in subclasses? Like
> klass.prototype.superclass = superclass
> ...in Class.Create. Is it because the *this*-reference would go out of
> scope?

You mean so you could reference it in instances via `this.superclass`?
Because of the grandchild problem. When you look at implementing a
superclass/subclass hierarchy with JavaScript, it's easy to create one
that will work one level deep (Parent->Child). Making it work
GrandParent->Parent->Child and deeper is difficult.

Remember that `this` always refers to the actual object, so if your
Child code calls the parent's `foo` via
`this.superclass.foo.call(this)` (recall the `.call(this)` is needed
to preserve `this`), that's fine and it works great. But what happens
when the Parent's code then does `this.superclass.foo.call(this)`?
Right! Exactly the same thing, because it's using the same property
(`superclass`) of the same object (`this`), and so it calls *itself*.
Infinite loop time.

Here are a couple of examples. I haven't used Prototype, but I've done
what Prototype would effectively be doing if it worked as you were
suggesting above:

http://jsbin.com/esalu5    <-- Parent->Child, all fine and dandy
http://jsbin.com/esalu5/2  <-- GrandParent->Parent->Child, loop city

There is *no* way to use a property on `this` (inherited from the
prototype or otherwise) to refer to the superclass, not that works
more than one level deep. It can't, because if you start with `this`,
all levels are working with the same data. That's why I based my
mechanism on the actual function objects themselves; they're unique,
and they're right there to hand. :-)

T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com

You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptaculous@googlegroups.com.
To unsubscribe from this group, send email to 
For more options, visit this group at 

Reply via email to