javascript - 我是否误解了继承概念?
问题描述
我试图弄清楚继承的正确使用。在下面的代码中,我试图实例化我的ReadingMaterial
类,并制作一系列书籍和杂志,继承自ReadingMaterial
. 我在这里正确使用继承吗?
// Define our class with constructor
class ReadingMaterial {
constructor(author, type, price, title){
this.author = author;
this.type = type;
this.price = price;
this.title = title;
}
}
// variable books containing 2 different books
var books = [
new ReadingMaterial("Lars Tvede", "Fagliteratur", "399kr","Supertrends"),
new ReadingMaterial("Rasmmus Tantholdt", "Faglitteratur","249kr","Med åbne øjne"),
new ReadingMaterial("Jussi Alder", "Skønlitteratur", "349kr","Offer 2117")
];
// feature that allows you to type `showMagazines();` in the console
// so we can see our magazines
function showBooks (){
console.log(books);
};
// variable magazine containing 2 different magazines
var magazine = [
new ReadingMaterial("Euroman", "Magasin", "99kr","Mick Øgendahl"),
new ReadingMaterial("Alt for damerne", "Magasin", "149kr","Boligindretning")
];
// feature that allows you to type `showMagazines();` in the console
// so we can see our magazines
function showMagazines() {
console.log(magazine);
};
解决方案
当您有两个实体,其中一个从另一个派生时,就会发生继承。例如,当您从父母之一继承眼睛颜色时,您俩的眼睛都是蓝色的。
请看一下这个例子(来源):
class Animal {
constructor(legs) {
this.legs = legs;
}
run() {
console.log(`Runs on ${this.legs} legs`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
const d = new Dog(4);
d.run(); // <- uses `run` method from `Animal`
d.bark(); // <- uses its own method
在您的示例中,您可以创建一个ReadingMaterial
类,然后创建类似Magazine
and的类,这些类Book
将从ReadingMaterial
.
继承是一个非常广泛且有时复杂的概念。很容易过度使用它并将类扩展得太深(例如,Animal
-> Dog
-> Husky
-> AlaskanHusky
)并且对实际发生的事情的跟踪松散。
我建议获取更多关于组合而不是继承的信息。
推荐阅读
- android - 使用正确的 androidx 实现和版本膨胀类 androidx.constraintlayout.widget.ConstraintLayoutaintLayout 时出错
- spring-boot - spring boot中绑定RSocket和gRPC的问题
- tensorflow - 如何使用 gpu 运行 dlib 人脸识别
- javascript - 如何使用正则表达式向数组添加空格
- flutter - Flutter:如何创建平滑的下拉菜单?
- meteor - 运行新的 Meteor 项目时出现“类型错误:semver 不是构造函数”?
- php - Laravel - 通过 log::info() 打印布尔值以记录?
- amazon-advertising-api - 亚马逊广告 API:ASIN 报告请求返回“缺少广告系列类型”
- apache-kafka - 如何使用 AZURE AD 为 Apache Kafka 集群配置 OAuth2 身份验证
- python - 使用 matplotlib 滚动重叠 3D 图像的 2D 切片