Wednesday, August 06, 2008

Update on Javascript

I've been meaning to write an update to my post on Javascript prototypes. Let me just show the updated code and then I'll explain what's changed.

Base = new Object();
Base.clone = function() {
var creator = function() {
this.constructor = arguments.callee
creator.prototype = this;
var result = new creator();
if (result.initialize)
result.initialize.apply(result, arguments);
return result;

Base.mixIn = function(properties) {
for ( var each in properties)
if (properties.hasOwnProperty(each))
this[each] = properties[each];
return this;

ZipCode = Base.clone().mixIn( {
initialize : function(standard, extension) {
this.standard = standard;
this.extension = extension;
toString : function() {
return this.standard + "-" + this.extension;

print(ZipCode.clone('56777', '4567'));

First thing you will notice is that I got rid of Object.prototype. I'll admit all of my recent Javascript code has been scripting on the server side. I do sometimes forget about all of the legacy code running on the browser(Adding properties to the Object.prototype can cause bugs in naive for loops). Not to fear, I created a Base object and put the clone and mixIn functions on it.

The next change is to the clone function where I introduced code that will setup the new clone if an initalize function is present. It calls the initialize function with the arguments passed into the clone function. I love doing things like this with Javascript.

Lastly, I had mixIn return itself. The reason is so that I could put the clone and mixIn on one line and only name the prototype once. This means I'm not duplicating the names of my objects and can more easily refactor the names. It also makes it easy to see the name and what prototype it is inheriting from.

I've always been infatuated with prototype-based programming languages. Javascript makes it possible to play with a real life prototype-based language. It saddens me to know that the next release of the standard introduces classes and that so many frameworks force classes into it. Once you get into using prototypes, you don't want to go back. You can use prototypes for a primitive versioning system, change tracking, and more that I haven't thought of yet. If you find more, let me know. Have fun using Javascript in new excting ways.

1 comment:

TECHHEAD said...

I'm with you on hoping classes never become a 'standard' part of Javascript. In fact, Javascript probably should have standardized the __proto__ property and left off 'new', 'instanceof', and the whole constructor charade. These things can be built on top of the prototype model.

Thanks for commenting.