0.4.4: Classes
Learning Objectives
Introduction
class Car {
// Define class properties in a constructor method
constructor(colour) {
this.colour = color;
this.odometer = 0;
}
// Define class methods within the class block
drive() {
this.odometer += 1;
}
}
// Create new "instances" of classes with the "new" keyword
const whiteCar = new Car("white");
const blackCar = new Car("black");
// Call class methods on instances of the class
whiteCar.drive();
blackCar.drive();
blackCar.drive();
// Retrieve class properties as we would with JS Objects
console.log(whiteCar.odometer); // 1
console.log(blackCar.odometer); // 2