Plunker - http://plnkr.co/edit/9tRSsBw2upSmXbF83D90 (code also at the end of this post )
I have a prototype function (generic) and another function which extends this prototype (specific). In the generic prototype I have a data object. I want the specific object to use this data object as a basis for it's own prototype data object data and to add keys to this data object instead of creating a new data object (which is what I think it's doing).
Plunker should illustrate what I mean.
Can someone tell me what prototype magic I'm missing to make specific also check the properties of the data ancestor instead of (as it seems to do) creating a new data object in its own prototype?
<script>
function genericDataObject ( dataObject ) {
if( !dataObject ) {
this.data = {};
} else {
this.loadDataObject(dataObject);
}
}
genericDataObject.prototype = {
//want all data objects to have the alwayshere property
data: {alwayshere: null},
loadDataObject: function (dataObject) {
//if our dataObject has a key that is set to null in data then replace null with that key's value
for (var key in dataObject) {
if( this.data[key] === null) {
this.data[key] = dataObject[key];
}
}
}
}
function specificDataObject ( dataObject ) {
genericDataObject.call(this, dataObject );
}
specificDataObject.prototype = new genericDataObject();
//add specific properties, shouldn't data be instantiated here with alwayshere as we've called new genericDataObject()????
specificDataObject.prototype.data.specificData1 = null;
specificDataObject.prototype.data.specificData2 = null;
var genericObject = new genericDataObject( { alwayshere: "here it is"} );
var specificObject = new specificDataObject( {alwayshere: "where is it?", specificData1: "this works"});
document.write( genericObject.data.alwayshere + "<br />"); //"here it is"
document.write( specificObject.data.alwayshere + "<br />" );// undefined
document.write( specificObject.data.specificData1);// "this works"
</script>