使用 Javascript 创建一个超类(继承)

Create a super class with Javascript (inheritance)

本文关键字:一个 超类 继承 Javascript 创建 使用      更新时间:2023-09-26

我对JavaScript中的OOP很陌生,并且正在尝试弄清楚如何创建一个类并从对象传递值(我知道JS没有类,所以我在玩原型)。在这个实践示例中,我尝试创建一个具有多个书架的类"库",每个书架都有几本书。我希望将书所在的书架(书架)从书架传递到书架,以及书架的数量(以及书架上的书)到图书馆。任何帮助将不胜感激。谢谢!

到目前为止,我的代码如下所示:

//LIBRARY 
function Library (name)
{
    this.name = name;
}
var lib = new Library("Public");
//SHELVES
Shelves.prototype = new Library();
Shelves.prototype.constructor=Shelves;
function Shelves (name, shelfnum)
{
    this.name = name;
    this.shelfnum = shelfnum;
}
var famous = new Shelves("Famous", 1);
var fiction = new Shelves("Fiction", 2);
var hist = new Shelves("History", 3);

// BOOKS
Book.prototype = new Shelves();
Book.prototype.constructor=Book;
function Book (name, shelf)
{
    this.name = name;
    this.shelf = shelf;
}
var gatsby = new Book("The Great Gatsby", 1);
var sid = new Book("Siddhartha",1);
var lotr = new Book("The Lord of The Rings", 2);
var adams = new Book("John Adams", 3);

正如 Ingo 在评论中所说,您的示例不适合继承。 继承是指对象与另一种类型共享特征。
继承示例:Bannana 函数将从 Fruit 函数继承。卡车函数将从汽车函数继承。

在这两种情况下,更具体的对象都继承自更广泛的类别。 当您可以使用多重继承时,您可能希望通过继承实用程序函数向对象添加功能:即,也许您的所有函数都可以从以某种方式记录错误的函数继承。 然后,所有函数都可以访问错误日志记录方法。

但是,在您的情况下,您应该采用不同的策略来使用数组或列表来构建程序,因为库具有许多架子,但架子不表现出与库相同的特征,因此不是继承的候选项。

以下是我将如何做到这一点:

function Library(name) {
     this.name = name;
     this.shelves = new Array();
}
function Shelf(name, num){
     this.name = name;
     this.num = num;
     this.books = new Array();
}
function Book(name) {
     this.name = name;
 }
var lib = new Library("Lib");
lib.shelves.push(new Shelf("Classics",1));
lib.shelves.push(new Shelf("Horror", 2));
//shelves[0] is Classics
lib.shelves[0].books.push(new Book("The Great Gatsby"));  
lib.shelves[0].books.push(new Book("The Lord of the Rings")); 
//shelves[1] is Horror
lib.shelves[1].books.push(new Book("Dr. Jekyll and Mr. Hyde")); 

console.log(lib.shelves.length); //# of Shelves in library
console.log(lib.shelves[0].books.length); //# of books in Classics shelf

希望这对您的项目有所帮助。 当你有项目需要Javascript中的OOP时,这可能会很有帮助:Mozilla:Javascript OOP