Javascript:从指针修改对象
Javascript: Modify an object from a pointer
我正在制作一个有三个类的数字图书馆:library、Shelf&书书架上摆放着一排本书。书有两种方法,入身和出身。当一本书被取消书架时,它应该设置从书架上删除它自己的实例,然后将它的位置属性设置为null。我该如何修改它所在的架子?在构造函数中,如果我更改this.location,它只会给这个属性一个新的值,而不是修改它所指向的变量。我觉得这真的很简单,我忽略了一些超级基本的东西。
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();
unshelf
方法的小问题,很容易解决:
this.unshelf = function() {
this.location.contents =
_.without(this.location.contents, this);
this.location = null;
}
然而,考虑shelf
和unshelf
应该是Shelf
的方法,而不是Book
的方法。此外,如果你必须有这种方法,用一个警卫包围它,就像这样:
this.unshelf = function() {
if (this.location) {
this.location.contents =
_.without(this.location.contents, this);
this.location = null;
}
}
几个小问题:
without
处理数组,并返回已删除元素的数组副本-原始数组未被更改。因此,您需要传递location.contents
,而不仅仅是location
,并将其重新分配回location.contents
。
此外,您将整本书添加到书架,然后尝试按名称删除它,这样它就不匹配并被删除。所以只需将this
传递给without
:
this.unshelf = function() {
if (this.location) {
this.location.contents = _.without(this.location.contents, this);
this.location = null;
}
}
相关文章:
- 使用AngularJS修改对象位置只需一次
- Reactjs:在修改对象之前,是否需要复制处于组件状态的对象
- 修改对象的原型不起作用
- 在 Javascript 中修改对象
- 通过Web服务修改对象列表,如何获取最终值列表
- 修改对象属性的方法中的 JavaScript 变量
- 在PouchDB/Barket.js中推送promise数组之前修改对象的值
- 就地修改对象javascript
- Backbone JS事件函数修改对象
- Javascript:从指针修改对象
- 使用Undercore在另一个对象内部修改对象内部的数组
- 修改对象's键而不创建新对象
- 在发布文档之前,如何在find()中修改对象级别的文档
- 在加载对象DOM之前修改对象DOM
- JS取回JSON解析是修改对象
- 继承和修改对象
- 在javascript中修改对象中的节点
- 修改对象存储的主键值
- 如何在修改对象后更新html中的数据
- Parse.com云功能-在发送到客户端之前手动修改对象字段