bartekw2213
bartekw2213

Reputation: 81

Why my new object based on class is not defined in the console?

I'm trying to make a BookList App (a little bit based on one of Traversy Media tutorial), that will add a book you typed in to the list visible on the site and to the local storage so after you refresh the website, the books you added before will be displayed. However I'cant create an object based on the Book class. After making submit event all the values from the inputs are assigned to the title, author, isbn variables. Then I'm using that variables to make a new book object based on Books class. Evertyhing looks good, the book is being add to the table but when I typed in book in the console, it says that the book is not defined. Why is that happening? Here is part of my JavaScript code:

//Creating a Book Class
class Book {
  constructor(title, author, isbn) {
    this.title = title;
    this.author = author;
    this.isbn = isbn;
  }
}

// Using submit button
document.addEventListener('submit', () => {
  title = document.querySelector('#title').value;
  author = document.querySelector('#author').value;
  isbn = document.querySelector('#isbn').value;

  const book = new Book(title, author, isbn); // Creating an object
  UI.addBookToTable(title, author, isbn); // Adding book to visible list
})

Upvotes: 0

Views: 59

Answers (1)

Artem Arkhipov
Artem Arkhipov

Reputation: 7465

Because variable book was declared inside the submit eventhandlers code. It is not visible outside the scope of that function. You should read about closures and scopes in javascript to better understand what I mean.

Anyway, if you would like to be able to type book in console and display the object, you need firstly assign it to the global object window. Something like this:

const book = new Book(title, author, isbn); // Creating an object
window.book = book; // now you attached it to the global scope
UI.addBookToTable(title, author, isbn);

After that you can call it from the console. Also, worth to note, that such practice is not good and you should not use it for any production purposes.

P.S. By the way, just FYI, the variable book is not used anywhere else in your code.

Upvotes: 4

Related Questions