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'
3
  • 5
    What does this have to do with React? There's no React code in your question. Commented Dec 29, 2018 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? Commented Dec 29, 2018 at 21:46
  • 1
    Have you tried new BookStore ? Commented Dec 29, 2018 at 21:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.