I'm new to JavaScript OOP and still playing around with it. I have put together a few specific questions over specific details throughout the code that are bothering me.
I wanted my Library
class constructor to be optional, the option to add a single book, multiple books or none at all, when creating the object. Is this a good way of achieving this goal?
class Library{
constructor(items){
this.books = [];
if(typeof items != 'undefined' && items instanceof Array){
this.books.push.apply(this.books, items); // Concat two arrays
} else if(typeof items != 'undefined') {
this.books.push(items); // Add one element
}
}
checkIn(id, renter){
var index = this.getIndex(id);
if(!this.books[index].available){
this.books[index].setDefaults();
renter.removeBook(id);
} else {
throw "Book Already Checked In";
}
}
checkOut(id, renter){
var index = this.getIndex(id);
if(this.books[index].available){
this.books[index].available = false;
this.books[index].currentRenter = renter.name;
// Adds current date to check out information.
var dateFormat = require('dateformat');
this.books[index].checkOutDate = dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT");
renter.addBook(this.books[index]); // Adds book to renter's inventory.
} else {
throw "Book Not Available";
}
}
getIndex(id){
for(var i = 0; i < this.books.length; i++){
if(this.books[i].id == id) return i;
}
return -1;
}
}
My Book
class works, but just does not feel correct at all and looks very sloppy. Any thoughts?
class Book{
constructor(title, pageCount, id){
this.title = title;
this.pageCount = pageCount;
this.id = id;
this.available = true;
this.currentRenter = null;
this.checkOutDate = null;
}
setDefaults(){
this.available = true;
this.currentRenter = null;
this.checkOutDate = null;
}
}
These are the only classes I did not really have any questions over. I am aware splitting these classes into two is completely unnecessary in this scenario, but I was just messing around with inheritance and never changed it back.
class Person{
constructor(name, age, phoneNumber){
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
}
}
class Renter extends Person{
constructor(name, age, phoneNumber, libraryID){
super(name, age, phoneNumber)
this.libraryID = libraryID;
this.books = [];
}
addBook(book){
this.books.push(book);
}
removeBook(id){
var index = this.getIndex(id);
this.books.splice(index, 1);
}
getIndex(id){
for(var i = 0; i < this.books.length; i++){
if(this.books[i].id == id) return i;
}
return -1;
}
}
Another general question: Am I accessing the class variables "formally"? It does not feel right setting a instance variable without a setter or returning a instance variable without a getter.