2013-10-26 95 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