Wednesday, January 30, 2008

Javascript Inheritance

Today, as I was working on developing an inheritance hierarchy based chain of classes in javascript, I realized just how truly possible OO was. Of course, it remains the world's giantest (yep, I know it ain't a word) hack. But, that being said, it's still cool.

Now, I can't take 100% claim for this, as I borrowed small segments of inheritance implementations from several javascript libraries, namely prototype and YUI, as well as the O'Reilly Definitive Guide to Javascript. However, this implementation is much better than all of those. To set it up, here is an example of use:

var C1 = function(var1) {
this.var1 = var1;
};
C1.prototype = {
test: function() {
alert(this.var1 + " is in C1");
}
};

var C2 = function(var1, var2) {
this.superclass(var1);
this.var2 = var2;
};
C2.prototype = {
test: function() {
this.superclass.test();
alert(this.var1 + " + " + this.var2 + " is in C2");
},
stuff: function() {
alert("stuff is just a regular function");
}
};

Object.extend(C2, C1);

var c1 = new C1("arg1");
var c2 = new C2("arg1", "arg2");

c1.test();
c2.test();


Doesn't that look familiar? Reminds me an awful lot of OO in a real OO language, like java. Here you go!
(edit: See "Javascript Inheritance, v2" above for the correct implementation.)

Object.borrow = function(destination, source) {
for (var key in source) {
destination[key] = destination[key] || source[key];
}

return destination;
};
Object.augment = function(destination, source) {
for (var key in source.prototype) {
destination.prototype[key] = destination.prototype[key] || sour$
}

return destination;
};
Object.extend = function(destination, source) {
var obj = function() {};
obj.prototype = source.prototype;

var proto = destination.prototype;
destination.prototype = new obj();
destination.prototype.constructor = destination;
for (var key in proto) {
destination.prototype[key] = proto[key];
}

var constructor = function() {
this.superclass.prototype.constructor.apply(this, arguments);
};

destination.prototype.superclass = constructor;
destination.prototype.superclass.prototype.constructor = source;
for (var key in source.prototype) {
destination.prototype.superclass[key] = source.prototype[key];
}

return destination;
};

0 comments: