Fullstack dev path. Question about constructors. [Project: Build a library]

Hello all,

So far in the exercise we learnt that we need to pass in values in our constructors to call them like so:

class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

But in this exercise: we are using only title in the constructor as following;

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

where as I did like so;

class Media {
  constructor(title, isCheckedOut, ratings) {
    this._title = title;
    this._isCheckedOut = isCheckedOut;
    this._ratings = ratings;
    isCheckedOut = false;
    ratings = [];
  }
  get title(){
      return this._title;
    }
    get isCheckedOut(){
      return this._isCheckedOut;
    }
    get ratings(){
      return this._ratings;
    }

Why cant we use all the common values that exist in three subclasses?
Thank you for your time.

We can set those common values/properties ( ._title , ._isCheckedOut , ._ratings ) in the constructor. However, the idea is to initially set ._isCheckedOut to be false for all objects of class Media, and to initially set ._ratings to be an empty array for those new Media objects/instances.

Your code does not do this: you change ischeckedOut and ratings, but that does not affect this._isCheckedOut and this._ratings

You can change your constructor to have default values for the parameters however.

class Media {
  constructor(title, isCheckedOut = false, ratings = []) {
    this._title = title;
    this._isCheckedOut = isCheckedOut;
    this._ratings = ratings;
  }

In this case,
if there is no second argument, false is used for it in the constructor;
if there is no third argument, [] is used for it in the constructor.

2 Likes

Thank you for your help. Now I understand the reason behind it.