Having a Java-background, when I switched to Javascript, I (lazily) tried to stick with what I knew regarding oop, i.e. a classical inheritance. I'm working on a web-app (that I made), and used this kind of inheritance. However, I'm considering to change my code and rewrite the OOP parts to do prototypal inheritance (two reasons: I read a lot that it's better, and secondly, I need to try the other way in order to have a better understanding of it).
My app creates data visualisations (with D3js, but it's not the topic), and organised my code this way:
function SVGBuilder( dataset ) {
this.data = dataset;
this.xCoord;
this.startDisplaying = function() {
// stuff
this.displayElement();
}
}
The displayElement()
method is defined in "classes" inheriting from SVGBuilder (which is more or less an abstract class). I then have:
function SpiralBuilder( dataset ) {
SVGBuilder.call( this, dataset );
this.displayElement = function() {
// stuff
};
}
SpiralBuilder.inheritsFrom( SVGBuilder );
I have several other "builders" based on the same structure.
The script calling the builder looks like this (it's a bit more complicated since it select the correct constructor based on the user input):
var builder = new SpiralBuilder( data );
builder.startDisplaying();
Now come the "conversion part". I read quite a lot about this, from Douglas Crockford's article, to parts of the Eloquent Javascript. In Aadit M Shah's comment, he proposes a structure which would look like this:
var svgBuilder = {
data: [],
xCoord: 0, // ?
create: function( dataset ) {
var svgBuilder= Object.create(this);
svgBuilder.data = dataset;
return svgBuilder;
},
startDisplaying: function() {
// stuff
}
}
However, at this point, I'm stuck. Firstly (technical question), can I declare variables (data, xCoord) without initialising them in this pattern? Just like a this.data;
? Secondly, how am I then suppose to create the inheritances? I simply manually put the corresponding functions in the prototype? Something like:
var spiralBuilder = builder.create( dataset );
spiralBuilder.prototype.displayElements = function() {
// Code to display the elements of a spiral
};
spiralBuilder.displayElements();
If I am correct, this mean that in the script calling the builder, instead of selecting the correct constructor (which won't exist anymore), I'll have to add/modify the methods in the prototype of a single builder instance. Is it how things should be done?
Or should I try to design my code in a completly different way? If it's the case, could you give me some advices/references for this?