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.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

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 )

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

%d bloggers like this: