Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
From the author of State and Behavior

State and Behavior

One interesting difference between class-based and prototype-based models is that there's no distinction between state and behavior in a language like JavaScript, while a language like Smalltalk makes a clear distinction between instance variables and methods.

It's common for a constructor in a class-based language to set up all of the instance variables (sometimes called fields) in the new object. So common, in fact, that C++ includes some special syntax for this purpose. (Mind you, C++ seems to include special syntax for anything that one of the people on the standards committee did more than once.)

In a prototype-based language like JavaScript, you can define the default values of all of these variables in the prototype. This technique is typically faster and uses less memory, due to the differential inheritance mechanism.

The state of an object in JavaScript is stored in a chain of lookup tables. If you create an object and initialize one of its fields, you're creating an entry in the table, which may require the table size to be expanded. On the other hand, if you set the value in the prototype, the lookup will just find the version in the prototype. You don't have to copy anything, and you don't have to allocate any space to store it.

A nice side effect is that you get copy-on-write behavior for free in JavaScript. It's quite common to use classes to share some state among instances in class-based languages, as a poor-man's emulation of this ability. You have a method in a superclass that returns a value and then two (or more) subclasses that always return the same value from all instances, and (optionally) another subclass that gets the value from the object's internal state. You can reduce memory usage when you have a collection of objects that typically share a lot of state.

In JavaScript, you can perform the same action easily via clones. For example, if you have an object representing a person, members of that person's family are likely to share the same surname and may share the same address and other details. You can create an archetypal family member object, and then create the others as clones of the original, simply modifying the properties that differ.

  • + Share This
  • 🔖 Save To Your Account