So, we talked about classes, but what are objects and why do we use them?
What is an object?
The formal definition of an object is the following. An object is a specific instance of a class.
This sounds really formal. Basically, an object is the actual version of the class. So, if we follow our Dog example, a specific dog would be a Leonberger or a Labrador Retriever.
We can create specific versions of each dog using the same class. We don’t have to re-write the class to create multiple dogs.
What does this look like in code?
Recall, here is our class:
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);
}
}
To create an instance of the class, we can do 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);
}
}
var leonberger = new Dog("Alice", "Leonberger", 70, "brown", "brown");
var lab = new Dog ("Lucy", "Lab", 35, "black", "black");
function setup()
{
createCanvas(800,600);
}
function draw()
{
background(0);
fill(255);
leonberger.eat();
lab.sleep();
}
And now we have two different dogs and one is eating and the other is sleeping.
Try the code in the earlier tabs to see the final result. Feel free to change values.