Search⌘ K
AI Features

Classes

Explore how to create and work with classes in JavaScript ES6, including constructors, static methods, getters, setters, and inheritance using extends and super. Understand how ES6 classes simplify prototype-based inheritance for cleaner and organized code.

Quoting MDN:

“Classes are primarily syntactic sugar over Javascript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.”

That being said, let’s review prototypal inheritance before we jump into classes.

Javascript (babel-node)
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function(){
console.log("Hello, my name is " + this.name);
}
const alberto = new Person("Alberto", 26);
const caroline = new Person("Caroline",26);
alberto.greet();
// Hello, my name is Alberto
caroline.greet();
// Hello, my name is Caroline

We added a new method to the prototype in order to make it accessible to all the new instances of Person that we created.

Ok, now that I refreshed your knowledge of prototypal inheritance, let’s have a look at classes.

 

Create a class #

There are two ways of creating a ...