Javascript:从指针修改对象

标签 javascript pointers object

我正在创建一个包含三个类的数字图书馆:图书馆、书架和书籍。书架上的内容是一系列书籍。书籍有两种方法,enshelf 和 unshelf。当一本书被取消上架时,它应该设置从其所在的书架中删除其自身的实例,然后将其位置属性设置为 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;
}

但是请考虑,shelfunshelf 应该是 Shelf 的方法,而不是 Book 的方法。另外,如果您必须使用此方法,请用防护罩包围它,如下所示:

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

关于Javascript:从指针修改对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954108/

相关文章:

javascript - 隐藏部分显示的 div

javascript - 使用 lodash 在对象数组中展平数组

c++ - std::unique_ptr 干扰某些 sf::RenderWindow 函数?

C 数组赋值使用大括号语法

javascript - JS - 在函数中覆盖 'this'

java - 如何修复列表中对象数组的不兼容类型

oracle - 如何在oracle中向对象类型列添加更多行

javascript - ReactJS onclick 向另一个元素添加或删除类

javascript - 从混合字符数组中仅检索整数值

c++ - read() 缓冲区有无效数据(指针问题?)