Question about Class constructor parameters

Been going through the Javascript course for a second time but doing all the projects that i skiped the first time around and am a bit lost when it comes to class constructors.

When do you need to use parameters and what are they used for ?

Like in the first library project it shows you needing to use only a title parameter.

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

But in the next project with the schools it shows you needing to add a parameter for each propertie.

class School {
  constructor(name, level, numberOfStudents) {
    this._name = name;
    this._level = level;
    this._numberOfStudents = numberOfStudents;

The parameters in the constructor of your second example are so that when you are creating an instance of that class for example a classroom of the School class you can pass it those objects as the properties or characteristics of the instance

1 Like

Ok so if i understand correctly you can only use super() on properties that are parameter of the constuctor ?

So on the first example i could call super(title) but on the second example i could use super(name, level, numberOfStudents) ?

Using a constructor you can pass on properties upon creating a new class instance. You can pass anything you like, any number of properties needed.

In this case we have two classes School and and Media. When we look at creating a new instance from Media, be it a Movie or a book, the only property shared by both is the title. Therefore only the title is passed on by the constructor and called during calling for a new class instance.

The checked out boolean is set to a default of false so no need to pass this. And the rating is empty.

Whereas when we look at the case of a School, Schools share a certain number of properties as listed, name, level of education and number of students. Therefore we conveniently pass multiple values in to the constructor.

3 Likes