Object#each: Useful JavaScript Game Extension #18

Part 18 of 256

Previously we discussed extending Object.prototype and adding a merge method. One of the big issues with messing with Object.prototype was that there was no standard and easy way to iterate over the non-prototype properties of an object. Remember that each method that I said was from the future? Today is that future.

/**
* Iterate over each property of this object, excluding prototype properties.
* It does this by excluding properties that aren't its own with `hasOwnProperty`
*
* @param {Function} iterator Receives two arguments for each property, the key and the value.
* @param {Object} [context] Optionally specifies what context the iterator will be called with.
*/
Object.prototype.each = function(iterator, context) {
  for(var key in this) {
    if(this.hasOwnProperty(key)) {
      iterator.call(context, key, this[key]);
    }
  }
 
  return this;
}
var candyPrices = {
  taffy: 0.95,
  rock: 1.25,
  lollipop: 0.50,
  licorice: 0.25
};
 
candyPrices.each(function(name, price) {
  alert("The price of " + name + " is $" + price);
});

This will allow us to iterate without having to write our own brittle for in iterators, and will be much more robust from breakage. If you are using for in you’ll need to decide whether or not prototype methods should be included. Here the decision already made, hopefully in a sane and generally robust manner.

Don’t worry about Array#each, it’s own prototype method will override this one so that array iteration is unaffected by this.

There are a few more useful Object.prototype extensions coming up, so stay tuned for the rest of the series.

Leave a Reply

Your email address will not be published. Required fields are marked *