Subj : Re: spidermonkey api To : netscape.public.mozilla.jseng From : Jens Thiele Date : Fri Nov 05 2004 11:52 am Brendan Eich schrieb: > Jens Thiele wrote: > >> I am currently mapping c++ class-based inheritance to prototype based >> inheritance. >> >> In JavaScript: >> >> function Base() { >> }; >> Base.prototype.baseMethod = ... >> >> function Sub() { >> // Base.call(this); >> }; >> >> Sub.prototype.__proto__ = Base.prototype; >> Sub.prototype.specialized = ... > > > Why aren't you setting Sub.prototype = new Base; ? > > /be IMHO Sub.prototype.__proto__ = Base.prototype; is the cleaner way to modell class-based inheritance via prototyping (each class is modelled by a prototype object) because: - new Base is in fact called to set __proto__ and we don't want to call the constructor on the sub prototype object (in the simple example above not a problem since the constructor function is a nop) - we must set the constructor property manually and afterwards it is enumerable (Sub.prototype.constructor = Sub;) see also: http://egachine.berlios.de/inheritance/ (compare figure 3 and figure 4) the assertions to be true in the example on http://egachine.berlios.de/inheritance/ (missing on that page) function assert(f){ if (!f()) throw Error("assertion failed: "+f.toSource()); }; base=new Base(0); assert(function(){return !base.specialized;}); assert(function(){return (base.baseMethod()+base.polymorph()==0);}); assert(function(){ return base instanceof Base && (!(base instanceof Sub)); }); sub=new Sub(90,0); assert(function(){return sub.specialized;}); assert(function(){ return (sub.baseMethod() +sub.polymorph() +sub.specialized()==100); }); assert(function(){return sub instanceof Base && sub instanceof Sub;}); Jens .