通过导入类方法来制作模块化javascript库,而无需整个类

时间:2019-03-23 12:01:59

标签: javascript

我正在尝试创建一个可重用的javascript库,例如books类,并具有createbook,checkforbook,修改book方法

我想这样使用

import Library, {checkForBook, modifyBook} from 'books'


Library.createBook({
 name : 'firstbook',
 year: 2012
})


checkForBook('firstBook')

modifyBook('firstBook',{
  name: 'secondBook'
})

我现在的问题是:不需要使用新的keywrod怎么做,以及如何使用不需要像Library.checkForBook这样的方法 并且仍然可以访问图书列表

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找

// library.js
export default class Library {
    …
}

// books.js
import Library from './library';

// creates a singleton:
export default const books = new Library();

export function checkForBook(name) {
    return books.checkForBook(name);
}
export function modifyBook(name, value) {
    return books.modifyBook(name, value);
}

// main.js
// imports the singleton, not the `Library` class
import books, {checkForBook, modifyBook} from 'books';

books.createBook({
 name : 'firstbook',
 year: 2012
});

checkForBook('firstBook');

modifyBook('firstBook', {
  name: 'secondBook'
});

答案 1 :(得分:0)

  const books = new Map(); // store the books somehow

  export function createBook({ name, year }) { // make them available as import { createBook } from ...
    const book = { name, year };
    books.set(name, book);
    return book;
  }

  export function checkForBook(name) {
    return books.has(name);
  }

  export function modifyBook(name, update) {
    if(!checkForBook(name))
      throw new Error("Cannot modify, book doesnt exist");
    Object.assign(books.get(name), update);
  }

  export default { // make them available as Library.createBook
    createBook,
    checkForBook,
    modifyBook
  };