Cannot read property of "push" in addRating [Library project]

class Media {
construtor(title) {
  this._title = title;
  this._ratings = [];
  this._isCheckedOut = false;
}

get title() {
  return this._title;
}

get isCheckedOut() {
  return this._isCheckedOut;
}

get ratings() {
  return this._ratings;
}

set isCheckedOut(newKeyTwo) {
    this._isCheckedOut = newKeyTwo;
}

toggleCheckOutStatus() {
 this.isCheckedOut = !this.isCheckedOut;
}

getAverageRatings() {
  let ratingsSum = this._ratings.reduce((accumulator, rating) => accumulator + rating);
  return ratingSum / this._ratings.length;
}

addRating(value) {
this.ratings.push(value);
}


};
class Book extends Media {
  constructor(title, author, pages) {
    super(title);
    this._author = author;
    this._pages = pages;
  }

  get pages() {
    return this._pages;
  }

  get author() {
    return this._author;
  }
};
class Movie extends Media {
  constructor(title, director, runTime) {
    super(title);
    this._director = director;
    this._runTime = runTime;
  }
};
const historyOfEverything = new Book('A Short History of Nearly Everything', 'Bill Bryson', 544);
historyOfEverything.toggleCheckOutStatus();
console.log(historyOfEverything.isCheckedOut);
historyOfEverything.addRating(4);
historyOfEverything.addRating(5);
historyOfEverything.addRating(5);
console.log(historyOfEverything.getAverageRating());

What are you doing here?
If it is to reference this._ratings, add a _ in of this.rating.push(value) this._rating //etc.
I think that will solve it, but I’m rusty on my JS.

Aside

If you add a setter for ratings you can use the getter in the addRating method.

set ratings (rating) {
    this._ratings.push(rating)
}
addRating (rating) {
    this.ratings = rating
}
1 Like

It still says:
/home/ccuser/workspace/learn-javascript-classes-build-a-library/app.js:34
this._ratings.push(rating)
^

TypeError: Cannot read property ‘push’ of undefined
at Book.set ratings [as ratings]

For whatever reason, super(title) is not invoking the parent constructor.

console.log(historyOfEverything.title)    //  undefined

Please post a link to the exercise page. Thanks.


Found the cause of the problem

class Media {
    construtor ...

Also, getAverageRating() instead of getAverageRatings().

I implemented the setter code from above and it works perfectly.

I also rewrote the method to use the getter…

 getAverageRating() {
    return this.ratings.reduce((a, b) => a + b) / this.ratings.length;
 }

What was wrong with
class Media {
construtor?

Spelling error. There is a missing, ‘c’.

1 Like