Lesson 6.2

Classes

Watch: Classes in JavaScript with ES6 - p5.js Tutorial

Video for 6.2:

A class is like a template or a blueprint for making an object. You declare a class with the keyword class followed by the name of the class, and then provide it with properties and methods.

The body of the class, the part between the curly brackets, is where you define constructors and methods. The constructor is for initializing an object – giving it initial properties. The methods are what the object can do.

Here is an example of declaring a Ball class with 5 properties; the x and y positions, the speeds along the x and y, and a diameter.

The class has been declared but does not do anything at this point. Here is the complete sketch file.

To create an instance of the Ball class we use the keyword new. Here we make a ball named ball1 of the class Ball.

If we type ball1 in the console we will see the object with its properties. We can also see the individual properties like ball1.x.

If we add a method to the class and call that method we will see it on the canvas.

To make the ball move we will add a move method. We will need to call display, move, and background in draw() to animate the motion.

Finally, we add the bounce method so that the ball bounces off the wall.

Example 6.2.1: A Bouncing Ball using a Class

Example 6.2.1

Exercise 6.2a: Define class Square with 4 properties, x,y,w,h, and 2 methods. The first method displays the square, the second, named grow, expand its height and width at the same rate. Make an instance of Square named square1; display it and have it grow.