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

Zhang Weiwu zhangweiwu at realss.com
Thu Jul 5 02:55:22 CDT 2007


在 2007-06-28四的 08:39 -0600,Ken Snyder写道:
> Zhang Weiwu wrote:
> > ...
> > 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;
> >   
> new Circle(); would work... it would simply set this.x and this.y to 
> undefined.
> >      B. the constructor is not re-used. FilledCircle() and Circle is
> >         almost identical but I cannot write in this way (tried doesn't
> >         work)
> > ...
> >
> > 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.
> >   
> This is exactly the approach of Prototype and Mootools.  They use a 
> constructor called 'initialize' which allows developers to either keep 
> the parent class's constructor or overwrite it in the child class.
> 
> var Class = {
>   create: function() {
>     return function() {
>       this.initialize.apply(this, arguments);
>     }
>   }
> };
> So Class.create(); just returns a constructor that does nothing except 
> call initialize.


I think there is an alternative method, although there might be very
good reasons not to use it. Recently I learnt to use "call" & "apply"

function FilledCircle(arg) {
	Circle.call(this, arg);
}

This is to call the superior class's constructor. I have used 'call'
myself several times and it seems working. A more detailed introduction
is available on Moz Developer Center. I guess everybody else on the list
knows this sort of things, just post info so that other newbies like me
on the list can benifit a little bit.




More information about the thelist mailing list