Objects In JavaScript

A “class” is a template for an object. You can’t do anything with a class, it just specifies behavior and structure.

An “object” is a instance of a class. This is something you can create and do things with.

In JavaScript all objects are prototyped or cloned from other objects. So if you want to create a second instance of an object, just clone it. But in practice it’s not that simple. You can’t just create an object literal and then invoke a method new variableName, variableName.clone().

So for this I’m going to talk about two types of objects, literals and what I’m calling a class template.

Object Literals
These are instances of classes. You can create them by naming the instance name (testObject1) and then adding variables and methods.

var testObject1 = {
  name: "test1",
  doit: function () {
    return 'this is a ' + this.name;
  }
};

Template Classes
These are just templates of objects. You can instanciate them and do things with them but they are not sufficient on there own. Here’s an example of this kind of class:

function testObject2() {
  this.name = "";
  this.doit = function() {
    return 'this is a ' + this.name;
  }
}

So to use this in real life just do the following:

var test1 = new testObject2();
var test2 = new testObject2();

With JavaScript you can create and mix these kinds of objects as the language permits it, but it’s usually a poor design choice.

Use Literals When:

  • Single uses objects
  • Minimal reuse or you don’t care about consistent behavior.

User Class Templates When:

  • You intend to reuse behavior
  • You are using a unit test framework to test behavior.

Personally I opt for always creating class templates it makes for easier unit testing and allows for greater reuse.