JavaScript has a quite uncommon way to implement inheritance: prototypal inheritance. We’ll see what that means later.
People coming from Java or Python or other languages had a hard time understanding the intricacies of prototypal inheritance, so the ECMAScript committee decided to sprinkle syntactic sugar on top of prototypical inheritance so that it resembles how class-based inheritance works in other popular implementations.
This is why, in 2015, the ECMAScript 6 (ES6) standard introduced classes.
This is important, it’s syntactic sugar: JavaScript under the hood didn’t change. It just added a nicer way to work with objects on top of the existing way.
A class definition
This is how a class looks.
class Person {
constructor(name) {
this.name = name
}
hello() {
return 'Hello, I am ' + this.name + '.'
}
}
A class has an identifier, which we can use to create new objects using new ClassIdentifier()
.
When the object is initialized, the constructor
method is called, with any parameters passed.
A class also has as many methods as it needs. In this case hello
is a method and can be called on all objects derived from this class:
const flavio = new Person('Flavio')
flavio.hello()
Static methods
Normally methods are defined on the instance, not on the class.
Static methods are executed on the class instead:
class Person {
static genericHello() {
return 'Hello'
}
}
Person.genericHello() //Hello
Class inheritance
Classes give JavaScript a more “classic” take on inheritance. Let’s describe it here, and then we’ll go into the “under the hoods” in the next lesson.
A class can extend another class, and objects initialized using that class inherit all the methods of both classes.
Inside a class, you can reference the parent class calling super()
.
If the inherited class has a method with the same name as one of the classes higher in the hierarchy, the closest method takes precedence:
class Programmer extends Person {
hello() {
return super.hello() + ' I am a programmer.'
}
}
const flavio = new Programmer('Flavio')
flavio.hello()
(the above program prints “Hello, I am Flavio. I am a programmer.”)
Classes do not have explicit class variable declarations, but you must initialize any variable in the constructor, although support for public class fields is in the works - and already in V8. JavaScript is always evolving.