在React组件中实例化JavaScript对象

时间:2018-12-29 21:38:56

标签: javascript

我有一个javascript类,其中包含一些数据和两个函数。

export class BookStore {
  constructor() {
    this._books = [
      { id: 1,title: "How to Learn JavaScript - Vol 1", info: "Study hard"},
      { id: 2,title: "How to Learn ES6", info: "Complete all exercises :-)"},
      { id: 3,title: "How to Learn React",info: "Complete all your CA's"},
      { id: 4,title: "Learn React", info: "Don't drink beers, until Friday (after four)"
    }]
    this._nextID= 5;
  }

  get books(){ return this._books;}

  addBook(book){
    book.id = this._nextID;
    this._books.push(book);
    this._nextID++;
  }
}

现在我要创建该类的对象,并控制台记录其书本项

const book =Object.create(BookStore)
console.log(book.books)

我尝试了几种方法,例如Object created方法,并尝试直接调用它。

import {BookStore} from './BookStore/BookStore.js'

1 个答案:

答案 0 :(得分:3)

您使用b而不是Object.create关键字来实例化该类。

使用以下代码:

new

const book = new BookStore(); console.log(book.books); 仅复制对象的原型,但不调用Object.create

您可以在相关问题中详细了解Understanding Object.create