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.

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’ }

  2. Pingback: Object#merge – Useful JavaScript Game Extensions 17

Leave a Reply

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