JavaScript Game Extensions: Object.extend

Part 16

Object.extend is an incredibly useful method in JavaScript. It can be used to dynamically augment object capabilities, create composite objects, and to provide a mechanism of inheritance.

Here is the method in it’s simplest form (from prototype.js):

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }

  return destination;
}

The method takes two arguments, a destination and a source. It then copies over each property from the source to the destination and returns the destination. This allows you to do things like:

var BLT = {
  bacon: true,
  lettuce: true,
  tomato: true
};

var Reuben = {
  cornedBeef: true,
  russianDressing: true,
  saurkraut: true,
  swissCheese: true
};

var sandwich = {};

Object.extend(sandwich, BLT);
Object.extend(sandwich, Reuben);
Object.extend(sandwich, {
  name: "custom",
  price: 6
});

Ok, so that’s pretty cool if we’re talking about sandwiches, but how often does that happen? Well if you imagine the sandwiches are classes and the toppings are methods then you’ve got a pretty modular system for constructing objects.

The extend method can be modified to add more smarts and power to it, but at it’s heart it is simply copying properties from one object onto another.

Hmm, all that talk about sandwiches has made me hungry.

Stay tuned for the rest of the series as well as my upcoming book {SUPER: SYSTEM} where I will go into much more detail.

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.

2 thoughts on “JavaScript Game Extensions: Object.extend”

  1. I think extend would be better as merge. So far most of your posts mimic how Ruby works. It’s really nice!

    { :a => ‘a’ }.merge(:b => ‘b’) => { :a => ‘a’, :b => ‘a’ }

    Like

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