0

我正在尝试制作一个 BookList 应用程序(基于 Traversy Media 教程之一),它将您输入的一本书添加到网站上可见的列表和本地存储中,因此在您刷新网站后,将显示您之前添加的书籍。但是我不能创建基于 Book 类的对象。发生事件后submit,输入中的所有值都分配给title, author,isbn变量。然后我使用这些变量来创建一个基于 Books 类的新书对象。Evertyhing 看起来不错,这本书正在添加到表格中,但是当我在book控制台中输入时,它说这本书没有定义。为什么会这样?这是我的 JavaScript 代码的一部分:

//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
})
4

1 回答 1

4

因为变量book是在提交事件处理程序代码中声明的。它在该功能范围之外是不可见的。您应该阅读javascript 中的闭包和作用域,以更好地理解我的意思。

无论如何,如果您希望能够book在控制台中输入并显示该对象,您首先需要将其分配给全局对象window。像这样的东西:

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);

之后,您可以从控制台调用它。此外,值得注意的是,这种做法并不好,您不应将其用于任何生产目的。

PS 顺便说一句,仅供参考,book您的代码中的其他任何地方都没有使用该变量。

于 2020-01-10T13:06:16.270 回答