In the book "WebGL - Up and Running," a unique custom geometry is created in a rather straightforward manner. However, what caught my attention was the penultimate line of code. Here's how it looked:
Saturn.Rings = function ( innerRadius, outerRadius, nSegments ) {
THREE.Geometry.call( this );
var outerRadius = outerRadius || 1,
...snip snip snip...
this.computeCentroids();
this.computeFaceNormals();
this.boundinSphere = { radius: outerRadius };
};
Saturn.Rings.prototype = new THREE.Geometry();
Saturn.Rings.prototype.constructor = Saturn.Rings;
My query revolves around why the author chose to use a constructor instance in the prototype chain. Wouldn't it be simpler for Saturn.Rings.prototype
to just be a clean slate inheriting from THREE.Geometry.prototype
? Shouldn't all inheritance-worthy components reside within THREE.Geometry.prototype
? Why bother making the prototype an instance of the Geometry constructor? (I acknowledge that the prototype chain remains intact since the new prototype inherits from THREE.Geometry
's prototype).
Moreover, in the second line of the aforementioned code, instances of Saturn.Rings
go through the THREE.Geometry
constructor, acquiring all they need from the construction process of THREE.Geometry
. Hence, there seems to be no necessity to repeat this with their prototype.
Lets now delve into how a similar geometry is handled within three.js itself:
THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
THREE.Geometry.call( this );
...snip snip snip...
}
this.computeCentroids();
this.mergeVertices();
};
THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
Much cleaner, right? The only hiccup is the oversight of setting the prototype's 'constructor' property to refer back to THREE.CubeGeometry
, but that's a minor detail.