首页 > 解决方案 > 对象作为 JavaScript 中的模型

问题描述

抱歉,如果我的问题真的很琐碎,只是想澄清一下。想象一下我有图书馆课,我有书课。例如,我有一些书,它们都存储在这个图书馆中。我的问题如下:我应该使用图书馆类作为模型来保存我的书籍对象吗?像这样:

class Library {
    static addBook(book){
        this.books.push(book);
    }

    static getBooksList() {
        return this.books;
    }
}

或者创建库的抽象类然后创建对象并将该对象用作存储会更好吗?(模型)

标签: javascript

解决方案


最灵活的方法是不要假设只有一个库,即使它在您当前的需求中可能是这样的。

所以我不会在你的库类上使用静态方法,而是使用库实例。这样它就更好地代表了现实生活——一本书有一天会在图书馆 A,而另一本书在图书馆 B。

class Library {
    constructor(name) {
        this.name = name;
        this.books = []; // Instantiate the books array.
    }
    addBook(book) {
        this.books.push(book);
        // Some extra handling if a book can only be in one library
        if (book.library) book.library.removeBook(book);
        book.library = this; 
    }
    removeBook(book) {
        let i = this.books.indexOf(book);
        if (i === -1) return;
        this.books.splice(i, 1);
        book.library = null;
    }
    getBooksList() {
        return this.books;
    }
}

class Book {
     constructor(title, author) {
         this.title = title;
         this.author = author;
         this.library = null;
     }
}

const book = new Book("1984", "George Orwell");
const library = new Library("The London Library");
library.addBook(book);
console.log("The book " + book.title + " is in " + book.library.name);

const otherLibrary = new Library("The Library of Birmingam");
otherLibrary.addBook(book);
console.log("The book " + book.title + " is in " + book.library.name);

如果书籍的数量会很大,您应该考虑使用 aSet而不是Arrayfor books。它将在O(1)而不是O(n)时间内提供书籍移除。


推荐阅读