WEEK: 15

Class Constructor Methods

In p5.js classes there is a constructor function. This should be the first function defined in the class.

The constructor function is always called when creating a new object from a class. Therefore you must have a constructor function. You can think about it as ‘constructing’ or building a new object. The constructor function is how a new object gets built.”

In the previous section, the class looked like this.

class Dog {
  constructor(name, breed, weight, eyeColor, hairColor ) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.eyeColor = eyeColor;
    this.hairColor = hairColor;
  }

  eat()
  {
    text(this.name + "is eating...", 100, 100);
  }

  sleep()
  {
    text(this.name + " is sleeping...", 200, 200);
  }
}

The constructor is defined at the top like this.

constructor(name, breed, weight, eyeColor, hairColor ) {

In this case, the constructor takes in five different arguments (name, breed, weight, eyeColor and hairColor).

So, when an object is created, it has those specific attributes or qualities.


Previous section:
Next section: