Saturday, March 24, 2007

Javascript OOP

Today I was trying to write a new "Class" module to be able to easily create an OOP patterns in Javascript. Actually, I had some 10 or 20 different variations. Most lacked one feature or another, or implemented things awkwardly, or simply became too big.

My goal (quite an ambitious one) was to create something as feature-packed as Dean Edwards' Base and at the same, as small as Kevin Lindsay's pattern. And be easily documentable.

After a whole day of writing and rewriting variations, I ended up with the same script I had written a while ago (except cleaner looking).

I was about done with Class patterns, but on my way to the shower, I had a "brilliant" idea: Simply append a string to the name of inherited members. Like so:

var Class=function() {};
Class.Extend=function(Class) {
 var ThisProto=this.prototype, SubClass=Class.Constructor||ThisProto.Constructor||function() {};
 SubClass.Extend=this.Extend, SubClass.prototype=Class;
 for (var Member in ThisProto) SubClass.prototype["undefined"==typeof Class[Member]?Member:Member+"Base"]=ThisProto[Member];
 return SubClass;

Yes, pretty stupid I know, but hey it's 7 lines of code and it keeps the correct scope in base methods. Here's a demonstration:

var Animal=Class.Extend({
 Constructor:function() {
  var Who="World";//private
  this.Who=function(Value) {return Who;}//privileged
 Say:function() {alert(this.Greeting+" "+this.Who());}//public
var Dog=Animal.Extend({
 Say:function() {
  this.SayBase();//calling the base method
  alert("Woof Woof");
var dog=new Dog()
dog.Say()//Hello World
 //Woof Woof

No comments:

Post a Comment