代码之家  ›  专栏  ›  技术社区  ›  Alexander Tarasenko

对象作为javaScript中的模型[关闭]

  •  0
  • Alexander Tarasenko  · 技术社区  · 6 年前

    假设我有图书馆课和图书课。 例如,我有一些书,它们都存放在这个图书馆里。 我的问题如下: 我应该使用Library类作为模型来保存我的图书对象吗? 这样地:

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

    还是先创建库的抽象类,然后创建对象并将此对象用作存储(model)更好

    1 回复  |  直到 6 年前
        1
  •  2
  •   trincot Jakube    6 年前

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

    所以我不会在库类中使用静态方法,而是使用库 实例

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

    如果书的数量很大,你应该考虑使用 Set Array 对于 books . 它将提供图书删除在 O(1) 时间而不是 O(n)