- What's New?
- Modifying the Prototype
- State and Behavior
- JavaScript COLA
- Objective-C in Smalltalk
Modifying the Prototype
Although there's no standard way of changing which object is used as a prototype, you still can modify an object's behavior via its prototype after construction, which is actually a fairly common idiom in JavaScript. For example, you can add a method that works on all string objects, simply by adding a function to one of String's prototype's slots. For example:
String.prototype.alert = function() { alert(this); };
This technique allows you to do things like "Message".alert(), which is a fairly trivial example, but also useful for replacing existing functionality. Several JavaScript libraries redefine some methods on DOM objects in this way to work around bugs in one or more implementations.
The prototype chain can be of any length. All of the standard objects are root objects, or inherit directly from a root object, but your objects can have very long chains of prototypes. If you have a group of objects with a common prototype, modifications to the prototype work in much the same way as modifications to a class in a language like Smalltalk, Ruby, or Objective-C.
The inability to modify the prototype chain makes JavaScript code slightly easier to understand than Self code. If an object begins life with a prototype, it will end life with the same prototype. This fact makes it easy to share common state and behavior between a group of objects.