我正在使用三个类编写一个库(在ES6 Javascript中):开放时间,书籍,书籍。和“主”类库(由以前的类组成)。
我得到的控制台错误如下:未捕获TypeError:无法在Books.set书籍[作为书籍]中设置undefined属性'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);
答案 0 :(得分:2)
var bookAmount = 0
没有初始化属性。 this.books = []
导致books
数组通过books
setter分配,与在类外分配的方式相同,this.books[this.bookAmount] = ...
使用books
和{{1}进行评估未定义。
应该是:
bookAmount
class Books {
constructor(){
this._books = [];
this.bookAmount = 0;
}
...
}
值是多余的,因为它已作为bookAmount
提供。正确的方法是:
this._books.length