13. Classes in ES6
ES6 introduces new class syntax. One thing to note here is that ES6 class is not a new object-oriented inheritance model. They just serve as a syntactical sugar over JavaScript’s existing prototype-based inheritance.
One way to look at a class in ES6 is just a new syntax to work with prototypes and contructor functions that we’d use in ES5.
Functions defined using the static
keyword implement static/class functions on the class.
class Task {
constructor() {
console.log("task instantiated!");
}
showId() {
console.log(23);
}
static loadAll() {
console.log("Loading all tasks..");
}
}
console.log(typeof Task); // function
const task = new Task(); // "task instantiated!"
task.showId(); // 23
Task.loadAll(); // "Loading all tasks.."
extends and super in classes
Consider the following code:
class Car {
constructor() {
console.log("Creating a new car");
}
}
class Porsche extends Car {
constructor() {
super();
console.log("Creating Porsche");
}
}
let c = new Porsche();
// Creating a new car
// Creating Porsche
extends
allow child class to inherit from parent class in ES6. It is important to note that the derived constructor must call super()
.
Also, you can call parent class’s method in child class’s methods using super.parentMethodName()
A few things to keep in mind:
- Class declarations are not hoisted. You first need to declare your class and then access it, otherwise ReferenceError will be thrown.
- There is no need to use
function
keyword when defining functions inside a class definition.