JavaScript Classes
JavaScript is an object-oriented programming language that uses classes to define objects and their behaviors. A class is a template for creating objects, which defines a set of properties and methods that the objects will have, providing a way to organize code into reusable components, making it easier to maintain and extend applications.
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(); // prints: "Honk"
console.log(myCar.colour); // prints: "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();
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); // prints: Object { colour: "red", number: 32 }
Take Away
JavaScript classes are a powerful tool for creating complex web applications. They provide a way to organize code into reusable components, making it easier to maintain and extend applications. By using inheritance, developers can create class hierarchies that provide a flexible and extensible architecture for their applications.