OO Javascript:未初始化数组

OO Javascript:未初始化数组,javascript,arrays,oop,ecmascript-6,initializer,Javascript,Arrays,Oop,Ecmascript 6,Initializer,我正在编写一个库(用ES6JavaScript),它有三个类:开放时间、书籍、书籍。和“主”类库(由前面的类组成) 我得到的控制台错误如下:UncaughtTypeError:无法设置undefined at Books.set Books[作为Books]的属性“undefined” 错误在setter中的Books类中 代码如下: 'use strict'; //OO library (Classes: Libary, Book, WorkingHours) class WorkingHou

我正在编写一个库(用ES6JavaScript),它有三个类:开放时间、书籍、书籍。和“主”类库(由前面的类组成)

我得到的控制台错误如下:UncaughtTypeError:无法设置undefined at Books.set Books[作为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
数组通过
books
setter分配,与在类外分配数组的方式相同,
this.books[this.bookamuty]=…
bookamuty
未定义的情况下进行计算

应该是:

class Books {
    constructor(){
        this._books = [];
        this.bookAmount = 0;
    }
    ...
}
bookAmount
值是多余的,因为它已经作为
this.\u books.length
可用。正确的方法是:

set books(book){
    this._books.push(book);
}

get books(){
    return this._books;
}

var bookAmount=0
不初始化属性
this.books=[]
使
books
数组通过
books
setter分配,与在类外分配数组的方式相同,
this.books[this.bookamuty]=…
bookamuty
未定义的情况下进行计算

应该是:

class Books {
    constructor(){
        this._books = [];
        this.bookAmount = 0;
    }
    ...
}
bookAmount
值是多余的,因为它已经作为
this.\u books.length
可用。正确的方法是:

set books(book){
    this._books.push(book);
}

get books(){
    return this._books;
}

不能有两个同名的属性
.books
不能既是(setter)方法又是数组,
.workingHours
如果bookin
只有getter并且是无限递归的,则不能设置它们。答案是正确的。请注意,您有两个不同的问题。试试本教程,它非常清楚地解释了Javascript OOP。谢谢你的指导和帮助。它现在开始工作了!不能有两个同名的属性
.books
不能既是(setter)方法又是数组,
.workingHours
如果bookin
只有getter并且是无限递归的,则不能设置它们。答案是正确的。请注意,您有两个不同的问题。试试本教程,它非常清楚地解释了Javascript OOP。谢谢你的指导和帮助。它现在开始工作了!非常感谢,它现在正按照我的预期工作:)非常感谢,它现在按照我的预期工作:)