Chapter 4: Factory design pattern: Closures as objects

Using closures as objects is one style of using Javascript. We will now look at the "Factory Design Pattern".

When I talk about objects, should not be confused with object literals. Object literals are instantiated by curly braces {}, but how would they be used as game objects? Consider this example:

var enemy = {
  position: {
    x: 32,
    y: 64
  },
  health: 10,
  yell: function () {
    alert('blargh!');
  }
};

This is an object literal for as enemy, but what if I want to spawn another enemy? The answer is simple: use a function!

var Enemy = function () {
  return {
    position: {
      x: 32,
      y: 64
    },
    health: 10,
    yell: function () {
      alert('blargh!');
    }
  };
};
// make a bunch of enemies
var enemy1 = Enemy();
var enemy2 = Enemy();

I like to name the functions that serve as the object factory with a capital. You could see them as constructors.

Every enemy spawned here has their own properties. Using closures, the objects can also have "private" variables. Rewriting the Enemy function: 

var Enemy = function () {
  // health is private
  var health = 10;
  return {
    position: {
      x: 32,
      y: 64
    },
    yell: function () {
      alert('blargh!');
    },
    damage: function () {
      health -= 1;
      if (health <= 0) {
        enemy.yell();
      }
    }
  };
};

health here is a private variable, since it can only be accessed from within the Enemy function.