2013-10-26 98 views
1

我对JavaScript的OOP很陌生,想弄清楚如何创建一个类并传递对象的值(我知道JS没有类,所以我正在玩与原型周围)。在这个练习的例子中,我试图创建一个有多个书架的书架,每个书架都有几本书。我正在寻找将书架上的书架,书架,架子(以及书架上的书架)数量传递给图书馆。任何帮助将不胜感激。谢谢!用Javascript创建一个超类(继承)

这里是我的代码看起来像至今:

//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); 
+4

OT:这没有意义。为什么'Shelves'从'Library'和'Book'从'Shelves'延伸?最好让图书馆拥有一个书架清单,每个书架都有一个书目清单。 –

+0

为了扩大@IngoBürk所说的内容,一个书架不是一个图书馆,一本书不是一个书架。 –

回答

2

由于英戈在注释中说,您的示例不会继承一个很好的候选人。继承是当一个对象与另一个类型共享特征时。
继承示例: 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

+0

这使得更有意义 - 感谢包含Mozilla源代码,这真的很有用! – epg388