“A class is a blueprint for creating objects, encapsulating data and methods.”
— MDN Web Docs
Is JavaScript an OOP language?
An object-oriented programming language is a language which organizes code into reusable objects. these objects are instances of classes which defines data and behaviours.
JavaScript is partially a OOP as It allows other paradigms (eg functional) while supporting the OOP.
Before ES6
JavaScript was not created to be a OOP language form its first days so the class syntax was not part of the language. Developers find a way to use OOP paradigm by using function constructors with prototypes concepts. Let's create a class Ingredient to prototype ingredients for a cake:
function Ingredient (name) {
this.name = name;
}
Ingredient.prototype.melt = function () {
console.log(this.name + ' is melting')
}
const butter = new Ingredient('butter');
butter.melt()
- We first defined a function constructor named
Ingredientacceptingnameas an argument. - Internally
Ingredientset the name of the instance to thenamepassed as an argument by using thethiskeyword. - We extend the definion of
Ingredientby overriding themeltmethod viaprototypeand use the availablethiskeyword to access the name of the instance. - We initialise a butter ingredient passing its
nameand then calling themeltmethod of it to log'butter is melting'.
Nowadays
JavaScript increases its support to OOP paradigm with ES6 by adding the classes and supporting constructors. Let's re-create our Ingredient class:
class Ingredient {
constructor(name) {
this.name = name
}
melt() {
console.log(this.name + ' is melting')
}
}
const butter = new Ingredient('butter');
butter.melt()
It might seem just a sugar syntax to do exactly the same thing we were able to do using the prototype and function contructors approach. In reality It allows us to extend our classes in a much easier and compact way:
class Butter extends Ingredient {
constructor(quantity) {
super('butter')
this.quantity = quantity
}
}
const butter = new Butter('400 g');
butter.melt()