2014-09-20 64 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; 
    } 
}