2014-09-20 87 views
0

我正在製作一個帶有三個類的數字圖書館:Library,Shelf & Book。書架上有許多書籍的內容。書籍有兩種方法,enshelf和unshelf。當一本書被取消時,它應該設置刪除它自己的實例,然後將它的位置屬性設置爲null。我怎樣才能修改它所坐的架子?在構造函數中,如果我改變this.location,它只會給該屬性一個新值,而不是修改它指向的變量。我覺得這很簡單,我忽略了一些超級基礎。Javascript:從指針修改對象

var _ = require('lodash'); 

//books 
var oldMan = new Book("Old Man and the Sea", "Ernest Hemingway", 0684801221); 
var grapes = new Book("The Grapes of Wrath", "John Steinbeck", 0241952476); 
var diamondAge = new Book("The Diamond Age", "Neal Stephenson", 0324249248); 

//shelves 
var shelf0 = new Shelf(0); 
var shelf1 = new Shelf(1); 

//libraries 
var myLibrary = new Library([shelf0, shelf1], "123 Fake Street"); 

//these need to accept an unlimited amount of each 
function Library(shelves, address) { 
    this.shelves = shelves; //shelves is an array 
    this.address = address; 
    this.getAllBooks = function() { 
     console.log("Here are all the books in the library: "); 
     for (var i = 0; i < this.shelves.length; i++) { 
      console.log("Shelf number " + i + ": "); 
      for (var j = 0; j < this.shelves[i].contents.length; j++) { 
       console.log(this.shelves[i].contents[j].name); 
      } 
     } 
    } 
} 

function Shelf(id) { 
    this.id = id; 
    this.contents = []; 
} 

function Book(name, author, isbn) { 
    this.name = name; 
    this.author = author; 
    this.isbn = isbn; 
    this.location = null; 
    this.enshelf = function(newLocation) { 
     this.location = newLocation; 
     newLocation.contents.push(this); 
    } 
    this.unshelf = function() { 
     _.without(this.location, this.name); //this doesn't work 
     this.location = null; 
    } 
} 


console.log("Welcome to Digital Library 0.1!"); 

oldMan.enshelf(shelf1); 
myLibrary.getAllBooks(); 
oldMan.unshelf(); 
myLibrary.getAllBooks(); 
+0

使用[] .splice()進行修改,像_.without功能的解決方案()進行復印。 – dandavis 2014-09-20 23:52:41

回答

1

小問題,你unshelf方法,容易補救:

this.unshelf = function() { 
    this.location.contents = 
     _.without(this.location.contents, this); 
    this.location = null; 
} 

考慮,但是,shelfunshelf應該是Shelf方法,而不是Book。另外,如果你必須有這種方法,圍繞着它有一個後衛,就像這樣:

this.unshelf = function() { 
    if (this.location) { 
     this.location.contents = 
      _.without(this.location.contents, this); 
     this.location = null; 
    } 
} 
+0

太棒了,謝謝:)) – ajHurliman 2014-09-21 01:37:14

1

幾個小問題:

without作品的陣列和返回刪除元素的數組的副本 - 原文未觸及。因此,您需要通過location.contents而不是僅僅location將其重新分配給location.contents

此外,您還將整本書添加到書架,然後嘗試通過名稱將其刪除,因此它不匹配並被刪除。所以只是通過thiswithout

this.unshelf = function() { 
    if (this.location) { 
     this.location.contents = _.without(this.location.contents, this); 
     this.location = null; 
    } 
}