Life before classes (pre-ES6)

JavaScript classes were introduced in ES6, so how life before then if one, say, wanted to create 2 variables with similar structures? We've have used constructor functions:

function Car(colour) {
  this.colour = colour;
}
Car.prototype.honk = function() {
  console.log("Honk");
};

const myCar = new Car('red');

myCar.honk(); // "Honk"
console.log(myCar.colour); // "red"

We can all agree that's not the best looking object blueprint implementation, particularly the method declaration.

New in ES6

Now, let's see how it's done using the `class` keyword:

class Car {
  constructor(colour) {
    this.colour = colour;
  }

  honk() {
    console.log("Honk");
  }
}

const myCar = new Car('red');

myCar.honk(); // "Honk"
console.log(myCar.colour); // "red"

Inheritance

Handling inheritance was a pain before ES6. Not anymore! 😀 Here is how it works:

class Car {
  constructor(colour) {
    this.colour = colour;
  }
}

class F1Car extends Car {
  constructor(number, colour) {
    super(colour);
    this.number = number;
  }
}

let bestCar = new F1Car(32, "red");
console.log(bestCar); // Object { colour: "red", number: 32 }

Next Steps