【发布时间】:2020-11-16 21:07:12
【问题描述】:
我正在创建一个 Animal 超类型构造函数,该构造函数的方法应该适用于所有“鸟”和“猫”对象。
- 我应该如何添加此原型以确保不会覆盖子类型的原型?
- 我可以在超类型原型中使用子类型原型的变量吗?
示例
function Animal() { }
Animal.prototype = {
constructor: Animal,
say: function(sound) {
console.log(`${sound}`);
}
};
function Cat(name) {
this.name=name
}
function Bird(name) {
this.name=name
}
Cat.prototype = {
constructor:Bird,
sound:'meow'
}
Bird.prototype = {
constructor:Bird,
sound:'Bach Op1 D minor'
}
Cat.prototype = Object.create(Animal.prototype)
Bird.prototype = Object.create(Animal.prototype)
//is this overwriting the prototype already set?
let myCat = new Cat("rupert")
console.log(myCat.name, myCat.say(), Cat.prototype)
【问题讨论】:
-
您是否有理由使用此语法而不是 classes?
-
刚开始玩,发现一些知识差距,就到了这里。事实上,类似乎更容易和更易读@Thomas
标签: javascript inheritance prototype