Learn JavaScript Classes – My Fun Word Game!

Object oriented programming (OOP) is when you have some variable, let’s call it “myCar”, but instead of just storing a single value inside it such as a number – we store various other variables and functions (AKA methods) inside it.

And it’s even cooler than that, because when we initialise myCar, the variables and functions that we store inside it, come from a template (AKA blueprint; officially called a class). This means we can declare as many copies of the blueprint as we need, simply by referring to this single class definition.

Whenever a variable becomes a copy of the class blueprint as described above, the variable is then called an object, which is said to be an instance of the class.

Programmers like OOP because of how it corresponds to real life situations. For instance, you might have an instance of a car class – consisting of a number variable for its year of manufacture, string variables for its make and model, a method to refill the tank with fuel, etc.

We use dot notation… so “.” after the object name, to access its properties and methods as they're called in JavaScript (in C++ for example we call them data members and member functions).

class carClass {
	year = 2015;
	make = "Ford";
	model = "Mustang"
	fuelLitres = 25;

	fuelMethod(cashInPounds) {
		 this.fuelLitres += Math.round(cashInPounds / 6.75);
	}
}
myCar = new carClass;
myCar.fuelMethod(50);
console.log("Year: " + myCar.year + " Make: " + myCar.make + " Model: " + myCar.model);
console.log("Fuel Level: " + myCar.fuelLitres + " Litres"); // displays "32 Litres"