Unexplainable undefined when passing values of a class?

Doing the last exercise of : https://www.codecademy.com/paths/web-development/tracks/webdev-intermediate-javascript/modules/learn-javascript-classes/projects/build-a-library

I create the class:

class CD extends Media{
  constructor(title, artist, songs){
    super(title);
    this._artist = artist;
    this._songs = songs;
  }
  suffle(){
    
  }
}

Then I create an instance:

const Norma = new CD('Norma', 'Mon Laferte', ['Mambo', 'Ronroneo', 'Deliras', 'Celos'] );

When I console.log(Norma.title) // returns Norma

But when I console.log(Norma.artist) // returns Undefined

However I have the exact structure with the class Movie, and all console.log returns correct values.
It looks like the title value from the parent class gets saved correctly, but the other two don´t.

This is my parent class:

lass Media {
  constructor(title) {
    this._title = title;
    this._ratings = [];
    this._isCheckedOut = false;
  }
  /*static generatePassword(){
   return Math.floor(Math.random() * 10000) + 0  
  }*/
  get AverageRating() {
		var sum =  this._ratings.reduce((partial_sum, a) => partial_sum + a);
   	return sum/this._ratings.length;
  }
  get title(){
    return this._title;
  }
  
  get isCheckedOut(){
    return this._isCheckedOut;
  }
  get ratings(){
    return this._ratings
  }
  toggleCheckOutStatus(){
    if (this._isCheckedOut === true){
      this._isCheckedOut = false;
    }
    else { this._isCheckedOut = true; }
  }
	addRating(number){
    this._ratings.push(number);
  }
}

In order to return a defined artist you would have to console.log(Norma._artist) since only _artist is defined right now. To return the artist using Norma.artist you need to set up a getter for the artist first, like you’ve done with the title.

Maybe have another look at the setters and getters exercise in that lesson and try to see what you’ve been missing.

3 Likes

lets look at this simple example:

class Example {
  constructor(hello){
    this.hello = hello;
  }
  
  get test(){
    return this.hello;
  }

}

example = new Example("hello world")
console.log(example.test);

calling the test getter, i get the hello property returned.

in JS we use the underscore that this property should use getters and setters, plus that we then can give the same name to the getter as the property. Its important to understand how its wired under the hood.

its important to understand that getters and setters are accessed the same way as you would access a property.

3 Likes