Tuesday, February 26, 2008

Reduce the Verbosity of Prototypal Class Definitions

I ran across some code like this recently:


function SomeClass(args){
...
}
SomeClass.prototype.firstMethod = function(args){ ... };
SomeClass.prototype.secondMethod = function(args){ ... };
SomeClass.prototype.thirdMethod = function(args){ ... };
...
...


Maybe, like me, you cringe when you see repetitious code. Maybe not. If not, return. So I got to thinking of a way to streamline this class.


function SomeClass(args){};
SomeClass.prototype = new (function(args){
   var me = this;
   me.firstMethod = function(args){ ... };
   me.secondMethod = function(args){ ... };
   me.thirdMethod = function(args){ ... };
   ...
})();

/* to test it, we'll create an instance and check if it has it's own [copy of] firstMethod */

var myClass = new SomeClass(args);
alert(myClass.hasOwnProperty('firstMethod'));
/* false, it does not have a local copy of the method */

No comments:

Post a Comment