WEEK: 7
Active: February 24th - March 1st
Work Due: March 2nd @ 11:59 PM

Creating Objects from Classes

A lot of discussions have occurred about classes and objects, yet you still do not know how to create an object from your class definition formally!

To create a new object “of class type X”, you need to call the new keyword, followed by the name of the class, including any constructor input parameters within parentheses trailing the class name. Remember, we did this with the Array class. It had the parentheses, but no parameters.

The following creates a new object of class type Person, and passes it two input parameters. The variable myPerson stores the new object.

let eyeColor = "blue";
let hairColor = "green";
let myPerson = new Person( eyeColor, hairColor );


Accessing an Objects Properties

To access the properties of an object, we will use the same “dot notation” as we learned about with objects’ data structures.

myPerson.eyeColor; // ← returns the value of 'myPerson's eyeColor.

We can also set object properties using this same notation.

myPerson.hairColor = "purple"; // ← sets the value of the property to purple

NOTE: Typically, when using classes and OOP paradigms, setting object properties with this notation is considered poor style. Direct access can lead to errors in code, and we will discuss this later.

Calling Object Methods

Object methods use the dot notation. Parenthesis is always added to the method name, regardless of whether input parameters are being passed into the method.

myPerson.walk(); // ← executes myPerson's method, 'walk'.

myPerson.timeToTravel(distance); // ← execute the method and pass it one input parameter value.



Previous section: