Using JavaScript how do I create a subclass that inherits values from the parent class? These values I need to inherit are defined by the parameters of the parent class. I want to have a one-to-many relationship between the parent class and the child class. Here is my example code where a Song consists of one or more Tracks:
function Song(x){
this.x = x;
}
function Track(y){
Song.call(this);
this.y = y;
}
Track.prototype = new Song;
var mySong = new Song(1);
mySong.guitar = new Track(2);
mySong.bass = new Track(3);
// goal is to output "1 1 2 3" but currently outputs "undefined undefined 2 3"
console.log(mySong.guitar.x + " " + mySong.bass.x + " " + mySong.guitar.y + " " + mySong.bass.y );
This question is similar to this sub-class question (http://stackoverflow.com/questions/1204359/javascript-object-sub-class) but uses variables defined by parameters. Right now when I try to call parentObject.childObject.parentVariable it returns undefined. What do I have to change in the code to make this work or is there a better way to code this one-to-many parent/child relationship?
So, it looks like you don’t want inheritance, you want composition.
I’ll try to find a good link.I didn’t find any good links and as I looked at your code more, I got more confused. Here is something that accomplishes what you want, but I’m not sure it’s really useful especially since it does a few things I would not normally consider.
Seems to me that a better solution would be: