Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Show HN: How I use JavaScript Prototypal Inheritance in my game inventory system (pixdeo.com)
45 points by mromanuk on Jan 20, 2015 | hide | past | favorite | 7 comments


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.


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...


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

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


thanks, will test!


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.


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.


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




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: