【发布时间】:2018-10-17 02:47:15
【问题描述】:
我正在编写一个包含三个类的库(使用 ES6 Javascript):开放时间、书籍、书籍。以及“主”类库(由以前的类组成)。
我得到的控制台错误如下:Uncaught TypeError: Cannot set property 'undefined' of undefined at Books.set books [as books]。
错误出现在 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);
【问题讨论】:
-
您不能拥有两个同名的属性。
.books不能既是(setter)方法又是数组,.workingHours和.booksIn如果只有 getter 并且是无限递归的,则不能设置 -
estus 答案是正确的。请注意,您在那里有两个不同的问题。试试这个教程,它非常清楚地解释了 Javascript OOP。 youtube.com/watch?v=PFmuCDHHpwk&t=3252s
-
感谢您的教程和帮助。它现在可以工作了!
标签: javascript arrays oop ecmascript-6 initializer