0

I have javascript class, that contains some data, and two functions.

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

Now I want to make an object of the class, and console log Its book items

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

I have tried several things, like the Object creates method, and trying calling it directly.

import {BookStore} from './BookStore/BookStore.js'
Laurens Deprost
  • 1,653
  • 5
  • 16
Kristoffer Tølbøll
  • 3,157
  • 5
  • 34
  • 69
  • 5
    What does this have to do with React? There's no React code in your question. – Lambda Fairy Dec 29 '18 at 21:41
  • 1
    `Object.create` should receive an object (can be an instance of a class) not a class. From JS point you may try `const book = new Bookstore` but I am not sure what you are trying to achieve. Please also clarify where do you run the code? Do you import the file in node? – HalilC Dec 29 '18 at 21:46
  • 1
    Have you tried `new BookStore` ? – Jonas Wilms Dec 29 '18 at 21:48

1 Answers1

3

You use Object.create instead of new keyword for instantiating the class.

Use the following code :

const book = new BookStore();
console.log(book.books);

Object.create just copies the prototype of the objects, but doesn't call the constructor.

You can read more about Understanding Object.create in the related question.

drinchev
  • 19,201
  • 4
  • 67
  • 93