Saturday, April 14, 2007

Javascript can be prototypical

The following JS code can be used to beget (a la Douglas Crockford, with a bit of _prototype spice) and to do a 'real' shallow clone. The object you clone will have the same parent as the cloned object, rather than just inheriting from Object.

This makes javascript work like a 'real' prototypical language (SELF) so we can follow the patterns that that implies.


function object(o){
if( !o ) {
o = this;
}
var builder = function(){};
builder.prototype = o;
var result = new builder();
result._prototype = o;
return result;
}

function clone(objectToClone, objectsParent) {
if(!objectToClone) {
objectToClone = this;
}
if(objectToClone._prototype) {
objectsParent = objectToClone._prototype;
}
if(!objectsParent) {
throw "no parent defined for this object";
}

// create new object with prototype
var result = object(objectsParent);

// copy over new stuff
for(var key in objectToClone) {
if( objectToClone.hasOwnProperty(key) ) {
result[key] = objectToClone[key];
}
}
return result;
}

Object.prototype.clone = clone;
Object.prototype.beget = object;