首页 > 解决方案 > 我是否误解了继承概念?

问题描述

我试图弄清楚继承的正确使用。在下面的代码中,我试图实例化我的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);
};

标签: javascript

解决方案


当您有两个实体,其中一个从另一个派生时,就会发生继承。例如,当您从父母之一继承眼睛颜色时,您俩的眼睛都是蓝色的。

请看一下这个例子(来源):

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类,然后创建类似Magazineand的类,这些类Book将从ReadingMaterial.

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

我建议获取更多关于组合而不是继承的信息。


推荐阅读