[thelist] question regarding to javascript class inheritance for big objects with fat constructors

Zhang Weiwu zhangweiwu at realss.com
Thu Jun 28 08:39:28 CDT 2007


Dear list

I have managed to get myself used to javascript class inheritance
machenism with this example:

function Circle(x, y) {
	this.x = x;
	this.y = y;
}

function FilledCircle(x, y) {
	this.x = x;
	this.y = y;
}

FilledCircle.prototype = new Circle(0, 0);

In this case FilledCircle become a class inheriting Circle. I have
noticed two problems in this example:
     A. In last line have created an object which I never actually use,
        the prototype of FilledCircle. I never needed a circle to be
        created with size 0;
     B. the constructor is not re-used. FilledCircle() and Circle is
        almost identical but I cannot write in this way (tried doesn't
        work)
        function FilledCircle(x, y) {
        	// this doesn't work
        	this.prototype.Circle(x, y);
        	// this doesn't work: tested on Firefox 2:
        	// inside Circle 'this' refere to the window object not the 
        	// object being created.
        	Circle(x, y);
        }

Both are not a problem for most javascript classes but in my case I got
problems because in my case my constructor is fat (50 lines) and created
a big object. I hit both problem A (creating large object that's not
used) and problem B (duplicate a very long constructor);

The solution in my head is to create a function "realConstructor" and
move all content of my current constructor to that function, and call
that function in the constructor.

function FatCircle(x, y) {
	/* do parameter validation check so that we don't really create 
	   a big fat object just to let FilledFatCircle to inherit it */
	if (typeof x == "integer" && typeof y == "integer")
		this.realConstructor(x, y);
}

FatCircle.prototype.realConstructor = function(x, y) {
.... [ here is my real fat constructor ]	
}

function FilledFatCircle(x, y) {
	/* yes, realConstructor is inherited from FatCircle */
	this.realConstructor(x, y);
}

/* this time I try to be smart: I created a very lightweight object only
   for inheriting purpose, see constructor of FatCircle */
FilledFatCircle.prototype = new FatCircle();

I am curious if people on the list have a better solution for this case?
Thanks a lot in advance!

Best Regards


-- 
Zhang Weiwu
Real Softservice
http://www.realss.com
+86 592 2091112




More information about the thelist mailing list