我正在编写一个图书馆(使用 ES6 Javascript),包含三个类:开放时间、书籍、书籍。以及“主”类库(由前面的类组成)。
我收到的控制台错误如下:Uncaught TypeError:无法在 Books.set books [as books] 处设置未定义的属性“undefined”。
错误出现在 setter 的 Books 类中。
这是代码:
'use strict';
//OO library (Classes: Libary, Book, WorkingHours)
class WorkingHours{
constructor(open, close, lunch){
this.open = open;
this.close = close;
this.lunch = lunch;
}
}
class Book {
constructor(title, category, author){
this.title = title;
this.category = category;
this.author = author;
}
}
class Books {
constructor(){
this.books = [];
//let books = new Array();
//let books = [];
var bookAmount = 0;
}
set books(book){
//this.books.push(book);
this.books[this.bookAmount] = book;
this.bookAmount++;
}
}
class Library {
constructor(workingHours, booksIn){
this.workingHours = workingHours;
this.booksIn = booksIn;
}
get workingHours() {
return this.workingHours;
}
get booksIn() {
return this.booksIn;
}
}
var workHour = new WorkingHours(900,1700,false);
var bookColl = new Books();
var newBook = new Book("Mastery", "Real Stories", "Robert Greene");
bookColl.books = newBook;
newBook = new Book("48 Laws of Power", "Slef-teaching", "Robert Greene");
bookColl.books = newBook;
var newLib = new Library(workHour, bookColl);
console.log(newLib);
最佳答案
var bookAmount = 0
不会初始化属性。 this.books = []
导致通过 books
setter 分配 books
数组,就像在类外部分配 this 一样.books[this.bookAmount] = ...
在 books
和 bookAmount
均未定义的情况下进行评估。
应该是:
class Books {
constructor(){
this._books = [];
this.bookAmount = 0;
}
...
}
bookAmount
值是多余的,因为它已经作为 this._books.length
提供。正确的方法是:
set books(book){
this._books.push(book);
}
get books(){
return this._books;
}
关于javascript - OO JavaScript : array not getting initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50211770/