gpt4 book ai didi

javascript - 我是否误解了继承的概念?

转载 作者:行者123 更新时间:2023-12-02 22:07:48 25 4
gpt4 key购买 nike

我正在尝试找出继承的正确用法。在下面的代码中,我尝试实例化我的 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);
};

最佳答案

当您有两个实体,其中一个实体派生于另一个实体时,就会发生继承。例如,当您从 parent 之一继承眼睛颜色时,那么你们都是蓝眼睛。

请看一下这个示例 ( source ):

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 类,然后创建 MagazineBook 等类,它们将从 继承某些内容阅读 Material .

继承是一个非常广泛且有时很复杂的概念。很容易过度使用它并将类扩展得太深(例如, Animal -> Dog -> Husky -> AlaskanHusky)并且对实际发生的情况缺乏了解。

我建议获取有关 composition over inheritance 的更多信息.

关于javascript - 我是否误解了继承的概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com