I'm trying to get the hang of javascript inheritance for multi-level inheritance frameworks. Basically what I've built is an abstract utility class that contains generic functions I can use in all other classes (including stuff like a self-contained simple set of ajax restful methods).
Below that I have generic abstract classes to define core functions to key types of classes that will fall under each. One of my 'types' for example, includes a collection of one of the other 'types'. (I'm trying to write some javascript classes to emulate doctrine entities and entity collections)
One of the things I tried to do, since all collections will have an associative array with the primaryId(key) and the entity object (value), was that I put the definition for the actual list of entities in the abstract layer. But I quickly found out that when I created more than one collection of the same type, any new ones I created had that property already populated with the values from the most recently populated prior one.
Bare-bones example:
myUtil = function() {
this.prop1 = "some value";
};
myUtil.prototype.setVals = function(data,child) {
child.populate(data);
};
myInter = function() {
this.vals = {z:'z'};
}
myInter.prototype = new myUtil();
myInter.prototype.populate = function(data) {
for(i in data) {
this.vals[i] = data[i];
}
}
myClass = function(data) {
// this.vals = {};
this.vals[0] = 0;
this.setVals = function(data) {
// do other stuff specific to inherited class
myInter.prototype.setVals(data, this);
}
// if data was passed in when instantiated, set values
if(typeof(data) == 'object') {
this.setVals(data);
}
}
myClass.prototype = new myInter();
var foo = new myClass({a:'a',b:'b',c:'c'});
var bar = new myClass();
bar.setVals({1:1, 2:2, 3:3});
console.log({foo:foo,bar:bar});
So in this example both object instances would end up with {a:'a', b:'b', c:'c', z:'z', 0:0, 1:1, 2:2, 3:3} for their vals property. If I uncomment the local initial setting of this.vals = {} in the child level(s), each will have the values I set to it plus the 0:0 but not the z:'z'.
First, am I doing this the right way or is there a better way to write this out so the values property cascade down and each child has a unique set of the properties when you make a 'new' one?
I can probably get by for now with declaring and modifying all at the child level, but in other languages, I've done some things with initializing part of a property's dataset in one level and filling in the remainder in the specific child classes. Is there a way to do something like this in js or do I have to split out the data even further and write in specific initialization methods/code to grab parent level data each time?