Tuesday, February 26, 2008


Have you ever seen code like this?


This won't work for all cases, but I often enjoy writing it like this:

if(!condition) return;

Note: if you are NOT minifying your code, the bottom method is probably leaner, but if you ARE minifying, stick with the top method.

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);
/* false, it does not have a local copy of the method */