archives

Prototypal inheritance misunderstood

Hey LtU, first post here :)

I have a question. I come from a mathematical background, so when I study something, I usually try to classify things in a more formal way than most. I was studying prototypal inheritance and was looking for a concise and correct definition this week. Not only is it hard to find proper descriptions that decouple prototype-based programming from JavaScript, it's even harder to find information on what makes the inheritance part tick.

The few that try to explain how prototypal anything works, get it blatantly wrong, confusing lots of different terms. One guy even called it synonimous to "the properties pattern", which was just ridiculous. Anyway...

From what I can tell, prototypal inheritance, which is at the core of languages like JavaScript, just means that it treats classes as first-class citizens, just like functional programming treats functions as first-class citizens. Of course, lots of small to big changes in how you design a language derive from that, giving shape to what what people see as prototype-based programming, but those are secondary, just like function-based programming usually gives rise to a "lambda syntax", which is also secondary.

Most often, here's what happens with prototypal inheritance:
- There's no explicit class type
- You can "inherit" from any object

What "inherit" means, depends on the language it seems, but the JavaScript library Stampit divides inheritance into a few behaviors, which looks like a clean way to describe it, to me. I haven't formalized it yet, should be a fun exercise. Basically, what I can see, so far:

- Creation (constructors, factory methods, etc)
- Delegation (parent objects, for example JavaScript __proto__, "classical" inheritance chains)
- Extension (copy/clone members, mixins, compare to jQuery extend for example)

JavaScript constructor functions ask you to provide a Creation function and use that to contruct a new object that is then added as a Delegation object. JavaScript's "Object.create" goes straight to delegation, the common "extend" pattern or any other kind of mixin pattern have Extension at their core. Classical inheritance usually forgoes Extension, working with mainly Creation and Delegation.

Feel free to provide more examples on how different languages use/combine these three and if these really cover the load. Thoughts on the "first-class classes" idea?