Classes

The classes constructor() is invocated when you use the 'new' keyword to create a new object. So all set-up goes in here (this.type = type etc). the 'this' keyword in the constructor() refers to the object created with the 'new' keyword, NOT this class itself.

Methods created inside classes are put into the newly created object's prototype (.__proto__) when you create a new object using the 'new' keyword. It's using 'prototypal inheritance'.

Methods can simply be created like so: lorem() { ... } rather than this.lorem = function() { ... }.

NOTE: you don't need to seperate methods with a comma, as you would in an object.

Classes can be extended using the 'extends' keyword, as seen in the example below. The Car class (that extends Vehicle) will inherit all of Vehicle's set-up and methods by... Inside Car's constructor() we call super() and pass in any required params. This is a lot less verbose than the old ways of extending the prototype chain.


class Vehicle {
  constructor(type) {
    this.type = type; // this refers to new object to be created
    this.isA = 'vehicle';
  }
  printType() {
    console.log(`This is a ${this.type}`);
  }
}

const boat = new Vehicle('boat');

boat.printType(); // "This is a boat"
console.log(boat.isA); // "vehicle"

//

class Car extends Vehicle {
  constructor(type) {
    super(type); // super calls Vehicle's constructor (we pass type to it)
    this.isA = 'car'; // over top of Vehicle's .isA
  }
}

const BMW = new Car('BMW');

BMW.printType(); // "This is a BMW"
console.log(BMW.isA); // "car"

//

console.log(boat); // NOTE: .printType in .__proto__
console.log(BMW);  // NOTE: .printType in .__proto__.__proto__