我对 JavaScript 中的 OOP 非常陌生,正在尝试弄清楚如何创建类并从对象传递值(我知道 JS 没有类,所以我一直在研究原型(prototype))。在这个练习示例中,我试图创建一个有多个书架的“图书馆”类,每个书架都有几本书。我希望将书在什么架子上(书架)从书到书架以及书架(和书架上的书)的数量传递给图书馆。任何帮助将不胜感激。谢谢!
这是我的代码到目前为止的样子:
//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
关于javascript - 使用 Javascript 创建父类(super class)(继承),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19612438/