javascript object helper


I've been working in Javascript quite a bit lately. This seems to be a recurring theme in my development career going back to 199x. As I always looked at javascript as a pseudo-language used to manipulate browser characteristics, I hadn't really taken a good look at it.

Recently, I found I was using a lot of the same code over and over again between pages. Good old copy/paste/molest style of coding. Ugh. And at first I though, "I should write procedures for this".

PROCEDURES?!? Isn't javascript object oriented? Some would argue that it is not. But it sure can act like it is. There are no classes, but there are objects with properties and methods. It supports encapsulation and aggregation. And it supports inheritance. There are a number of different ways of achieving inheritance. I am not going to go into all of them in this posting. What I know, I learned from the Master anyway.

I decided to create an object that would encapsulate my common object manipulations; create a new instance of an existing object, extend an objects properties, and create a new object through multiple inheritance. With these three simple tools, I can accomplish quite a bit.

The following is the code as of this writing:

var objectHelper = {
  clone: function (originalObject) {
      var returnObject;
      function interstitial() {};
      interstitial.prototype = originalObject;
      returnObject = new interstitial();
      returnObject.uber = originalObject;

      return returnObject;
  },

  extend: function (originalObject, newProperties) {
      var returnObject = this.clone( originalObject );
      for ( var prop in newProperties ) {
          returnObject[prop] = newProperties[prop];
      }

      return returnObject;
  },

  assemble: function(objectHash) {
      var returnObject = {};
      for ( var obj in objectHash ) {
          returnObject[obj] = this.clone(objectHash[obj]);
      };
      return returnObject;
  }
};

clone creates a new object based on the one you pass to it. This seems simple enough, but it encapsulates code I commonly use. The benefit here is that manipulation of the new objects base properties do not alter the original objects properties. This is a common hassle with javascript objects

extend creates a new object based on the one you pass it and a corresponding object literal (or named object). The resultant object has all of the properties of the original, plus all of the additional properties provided in the second parameter.

assemble accepts any given number of objects as parameters and assembles a single object comprised of all the objects passed in.


2 comments:

  1. Interesting ideas - absent concrete usage examples ;)

    ReplyDelete
  2. A concrete usage of this?
    Just an unuseful complicate DSL

    ReplyDelete