Lesson 6.3

Constructors with Arguments

Watch: Constructor Arguments with Classes in JavaScript- p5.js Tutorial

Video for 6.3

The whole point behind making a class is so that we can efficiently create multiple instances of objects. This point is defeated if we give the properties literal values – all of our objects will be the same unless we use the random function to generate some variation.

How do we give the objects we make from a class different initial properties?

By passing it arguments.Here is an example form the previous lesson. It has literal values for all parameters.

How can we modify this so that the objects we make can have different initial values? Add parameters.

When used to make an instance this means, let the value of x for this ball be whatever x value is passed to it as an argument. The same holds for the other parameters.

Now when we make two instances of the ball class we can vary the initial properties as shown here.

And it is easy to display, move, and bounce both balls.

Example 6.3.1: The bouncng ball with added parameters to the constructor function.

Example 6.3.1

Exercise 6.3a: Add parameters to your class Square from exercise 6.2a. Make two instance of Square named square1 and square2 and have them both grow.