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

Ken Snyder kendsnyder at gmail.com
Thu Jun 28 09:39:00 CDT 2007


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 am curious if people on the list have a better solution for this case?
> Thanks a lot in advance!
>
> Best Regards
>
>   
There are tons of inheritance schemes in JavaScript, some even emulating 
classic OO inheritance.  Try searching in Google for more info.

-- Ken Snyder



More information about the thelist mailing list