Better Living Through JavaScript Closures

My original design for the javascript version of Island Interloper, I had a rather simplistic serialization scheme.

All of the data for the game was in a global object called “game”.

This was all just data, so that it could be made into a JSON string and then stored elsewhere, and similarly come from a JSON string and parsed into the original object.

This works pretty well, but there were some issues with it.

  1. I had some functions within the game data. Function objects are not JSON-able, and would be lost when saving, and missing when loading.
  2. I wound up with a lot of rather unwieldy expressions, like game.islands[game.avatar.island].name and so on. After first wrapping this up into functions to make it slightly easier, I attempted wrapping them into proxy objects, which made it even uglier, so I decided to do a different design.
  3. Not all parts of the game object need to be serialized. The commodity list doesn’t change ever, similarly the list of ships and crew members.  Do not serialize what you don’t need to.

So, after this minor setback, I’m well on the way to having a better design.

Except that I think that some of the functions used within the objects that now comprise the Game object should make better use of closures.

For example, the createRandomName function is only needed by Game.Islands to generate a list of random names.

Also, currently everything relies upon the global Game object to get data from other aspects of the game, like utility functions and actions.  I think that closures would be another better way to get the data.  Time will tell.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s