JavaScript 子类 - 如何继承参数中定义的父值?
如何使用 JavaScript 创建一个继承父类值的子类?我需要继承的这些值是由父类的参数定义的。我希望父类和子类之间有一对多的关系。这是我的示例代码,其中一首歌曲由一个或多个曲目组成:
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 );
这个问题类似于这个子类问题(http://stackoverflow.com/questions/1204359/javascript-object-sub-class),但使用定义的变量通过参数。现在,当我尝试调用parentObject.childObject.parentVariable时,它返回未定义。我必须在代码中更改哪些内容才能使其正常工作,或者是否有更好的方法来编码这种一对多父/子关系?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以,看起来你不需要继承,你想要组合。
我会尝试找到一个好的链接。我没有找到任何好的链接,当我更多地查看您的代码时,我变得更加困惑。这是可以实现您想要的功能的东西,但我不确定它是否真的有用,特别是因为它做了一些我通常不会考虑的事情。
在我看来,更好的解决方案是:
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: