

Show HN: How I use JavaScript Prototypal Inheritance in my game inventory system - mromanuk
http://pixdeo.com/articles/Inventory%20Items%20and%20prototypal%20inheritance/

======
sago
There's a benefit of prototypal inheritance that isn't touched on here, but is
significant enough that I've implemented it a couple of times in game engines.
One of those things that, once you've seen it, pops up again and again. A
reason I like Javascript as a language.

It is having three layers of instantiation.

Typically in a data-driven game engine you have some base class that handles
the behavior of, say, a collectible. (In a modern engine this would be a
component, rather than a base class).

Then you load data and instantiate a number of those components for different
types of collectible: health, powerup, etc.

Then you instantiate those for a specific collectible (the health pack at
location X,Y,Z in level A).

That doesn't map elegantly onto the class/instance dichotomy. The mapping is
tricky enough that there are different ways of doing it: you can have a
different kind of class in the middle layer that acts as a factory for your
third layer instances; you can have an 'archetype' mechanism, where instances
at the second level are copied to make instances at the third; or you make
instances at the third level have a reference to their 'type' (instances at
the second) and delegate queries through to them. There are many other
approaches.

But that three layer data-driven problem goes away when you can just inherit
as many times as you like.

In most large game engines, there is a poorly architected buggy version of
prototypical inheritance.

~~~
nordsieck
If you haven't seen this before, you might like this Steve Yegge article about
prototypal inheritance.

[http://steve-yegge.blogspot.com/2008/10/universal-design-
pat...](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html)

------
vkjv
Tangential to the story, but, using `_.defaults` prevents the extra object
allocation and reduces the syntax.

`var jalapeño = _.defaults(jalapenoFromJSON, apple);`

~~~
mromanuk
thanks, will test!

------
deedubaya
Prototypical Inheritance is one of the things I love most about Javascript,
and yet, is usually something a lot of dev's don't like/understand about JS.

Do you write Javascript? Do the world a favor and learn how to use Prototypes
instead of using classes for everything.

~~~
mromanuk
amen! I think the problem is that most of us, came to Javascript from C++/Java
where classical inheritance is dominant and pretty much forced that paradigm
over the more natural ones.

------
deeviant
I never found inventory object hierarchies to be a sore point in developing
games (hobby games admittedly).

