Classes

We'll cover the following...

Classes are now here in JavaScript, up until now we have had many ways to ways to emulate this concept. For awhile now we have been emulating classes with the use of functions. The introduction of classes to the languages was met with a lot of opinions, some positive, most negative. Classes have been an important part of many languages, as they allow you a means to create blueprints for common elements in your program.

Class emulation in JavaScript

In JavaScript we can use functions and objects to emulate classes. Functions can be used to create constructors that, when used with the new keyword, can instantiate new objects.

Press + to interact
function Plane() {
this.wings = 2;
this.speed = 100;
this.altitude = 0;
}

Convention has it that constructors are named with a capital first letter. To create a new Plane we use new.

Press + to interact
const myPlane = new Plane();

If we want to add methods to the Plane we can use the prototype property to add them on.

Press + to interact
Plane.prototype.fly = function() {
this.altitude = 30000;
};

This will allow us to use the fly method on our new myPlane ...