martini21
martini21

Reputation: 1

OO Javascript: array not getting initialized

I'm programming a library (in ES6 Javascript) with three classes: opening hours, book, books. And the "main" class library (which consists of the previous classes).

The console error I'm getting is the following: Uncaught TypeError: Cannot set property 'undefined' of undefined at Books.set books [as books].

The error is in the Books class in the setter.

Here is the code:

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

Upvotes: 0

Views: 103

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

var bookAmount = 0 doesn't initialize a property. this.books = [] causes books array to be assigned through books setter the same way it would be assigned outside class, this.books[this.bookAmount] = ... is evaluated with both books and bookAmount being undefined.

It should be:

class Books {
    constructor(){
        this._books = [];
        this.bookAmount = 0;
    }
    ...
}

bookAmount value is redundant, because it's already available as this._books.length. The proper way to do that is:

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

get books(){
    return this._books;
}

Upvotes: 2

Related Questions