【问题标题】:Javascript: Modify an object from a pointerJavascript:从指针修改对象
【发布时间】:2014-09-21 07:45:17
【问题描述】:

我正在制作一个包含三个类的数字图书馆:图书馆、书架和书籍。书架上的内容是一系列书籍。书籍有两种方法,enshelf 和 unshelf。当一本书下架时,它应该设置从它所在的书架上删除它自己的实例,然后将它的位置属性设置为空。如何修改它所在的架子?在构造函数中,如果我更改 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();

【问题讨论】:

  • 使用 [].splice() 进行修改,像 _.without() 这样的功能性解决方案进行复制。

标签: javascript pointers object


【解决方案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;
    }
}

【讨论】:

    【解决方案2】:

    几个小问题:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多