Javascript 从超类型继承属性时出现问题

Javascript 从超类型继承属性时出现问题,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,我正在创建一个Animalsupertype构造函数,它有一个方法可以用于所有“bird”和“cat”对象 我应该如何添加此原型以确保不覆盖子类型的原型 我可以在超类型原型中使用子类型原型的变量吗 示例 function Animal(){} 动物原型={ 建造师:动物, 说:功能(声音){ log(`${sound}`); } }; 功能类别(名称){ this.name=name } 功能鸟(名称){ this.name=name } 类别原型={ 建造师:小鸟, 声音:“喵” } B

我正在创建一个
Animal
supertype构造函数,它有一个方法可以用于所有“bird”和“cat”对象

  • 我应该如何添加此原型以确保不覆盖子类型的原型
  • 我可以在超类型原型中使用子类型原型的变量吗
示例

function Animal(){}
动物原型={
建造师:动物,
说:功能(声音){
log(`${sound}`);
}
};
功能类别(名称){
this.name=name
}
功能鸟(名称){
this.name=name
}
类别原型={
建造师:小鸟,
声音:“喵”
}
Bird.prototype={
建造师:小鸟,
声音:“巴赫Op1 D小调”
}
Cat.prototype=Object.create(Animal.prototype)
Bird.prototype=Object.create(Animal.prototype)
//这是否覆盖了已设置的原型?
让我的猫=新猫(“鲁伯特”)

console.log(myCat.name,myCat.say(),Cat.prototype)
您可以使用
Object.assign
继承动物的原型,但也可以添加自己的字段和方法。另外,您需要使用
this.sound
来访问实例本身的属性

Animal.prototype = {
  constructor: Animal,
  say: function() {
    console.log(`${this.sound}`);
  }
};
//...
Cat.prototype = Object.assign(Object.create(Animal.prototype), {
  constructor:Bird,
  sound:'meow'
});
Bird.prototype = Object.assign(Object.create(Animal.prototype),{
  constructor:Bird,
  sound:'Bach Op1 D minor'
});
演示:

function Animal(){}
动物原型={
建造师:动物,
say:function(){
log(`${this.sound}`);
}
};
功能类别(名称){
this.name=name
}
功能鸟(名称){
this.name=name
}
Cat.prototype=Object.assign(Object.create(Animal.prototype)){
建造师:小鸟,
声音:“喵”
});
Bird.prototype=Object.assign(Object.create(Animal.prototype)){
建造师:小鸟,
声音:“巴赫Op1 D小调”
});
//这是否覆盖了已设置的原型?
让我的猫=新猫(“鲁伯特”)

console.log(myCat.name,myCat.say(),Cat.prototype)
您可以使用
Object.assign
继承动物的原型,但也可以添加自己的字段和方法。另外,您需要使用
this.sound
来访问实例本身的属性

Animal.prototype = {
  constructor: Animal,
  say: function() {
    console.log(`${this.sound}`);
  }
};
//...
Cat.prototype = Object.assign(Object.create(Animal.prototype), {
  constructor:Bird,
  sound:'meow'
});
Bird.prototype = Object.assign(Object.create(Animal.prototype),{
  constructor:Bird,
  sound:'Bach Op1 D minor'
});
演示:

function Animal(){}
动物原型={
建造师:动物,
say:function(){
log(`${this.sound}`);
}
};
功能类别(名称){
this.name=name
}
功能鸟(名称){
this.name=name
}
Cat.prototype=Object.assign(Object.create(Animal.prototype)){
建造师:小鸟,
声音:“喵”
});
Bird.prototype=Object.assign(Object.create(Animal.prototype)){
建造师:小鸟,
声音:“巴赫Op1 D小调”
});
//这是否覆盖了已设置的原型?
让我的猫=新猫(“鲁伯特”)

log(myCat.name,myCat.say(),Cat.prototype)
。但是在代码片段中,对“say”的调用仍然返回
未定义的
?@misternobody您没有从函数返回任何内容。您只调用了
console.log
,这就是为什么它隐式返回
undefined
.uhu?我很困惑,我认为应该有一些声音输出anyways@misternobody然后编写
返回this.sound
而不是
console.log(this.sound)
。哦,对不起,我没有在第一行看到单词meow。谢谢太神了但是在代码片段中,对“say”的调用仍然返回
未定义的
?@misternobody您没有从函数返回任何内容。您只调用了
console.log
,这就是为什么它隐式返回
undefined
.uhu?我很困惑,我认为应该有一些声音输出anyways@misternobody然后编写
返回this.sound
而不是
console.log(this.sound)
。哦,对不起,我没有在第一行看到单词meow。谢谢你使用这种语法有什么原因吗?开始玩吧,注意到一些知识上的差距,就在这里结束了。事实上,类似乎更容易阅读@ThomasIs这里有一个你为什么要使用这种语法的原因吗?开始玩吧,注意到一些知识的差距,然后在这里结束。事实上,类似乎更容易阅读@Thomas