ES6 classes

ECMAScript 6 added class keyword. Now we can declare classes such other languages. Learn how to declare a new class and
how to create an instance to use its method and properties on the right way.

Get started

The following code we see how a basic class is implemented in ES6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Class declaration
class Foo{

// Constructor
constructor(name){
this._name = name;
}

// Getter
get name(){
return this._name;
}

// Setter
set name(name){
this._name = name;
}

// Static method
static sayHello(){
console.log('hello');
}
}

// Create an instance of Foo
const f = new Foo('John');
console.log(f.name); // 'John'
f.name = 'Walter';
console.log(f.name); // 'Walter'
Foo.sayHello(); // 'hello'

First we have the builder, which initializes the properties of the instance. Then we see that we have two methods that you can use to obtain and/or change the property name. We also have a static method to use as a class and not an instance, that is why to use it we don’t need an instance if not that we access directly with the class.

Extending a class

Sometimes we find ourselves in the need to extend a class. ES6 was not going to be less and offers us that possibility perfectly. Below is an example (we keep the Foo class identical).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Foo{ ... }
class Bar extends Foo{
constructor(name){
super(name);
}
get name(){
return 'This is a Bar instance, named:' + super.name;
}
set name(name){
super.name = name;
}
static sayHello(){
console.log('Bar hello');
}
}

const b = new Bar('John');
console.log(b.name); // 'This is a Bar instance, named: John'
b.name = 'Walter';
console.log(b.name); // 'This is a Bar instance, named: Walter'
Bar.sayHello(); // 'Bar hello'

As we can see, it is quite simple to extend classes. Its mechanism is very similar to the one we are used to in other programming languages, so there won’t be a big difference to adapt you to the ES6 classes.

The keyword used is extends.

Import/Export ES6 classes

The usual way I use classes with Node.js is as follows:

1
2
class Foo{ ... }
module.exports = Foo;
1
2
3
const Foo = require('./foo');
class Bar extends Foo{ ... }
module.exports = Bar;
1
2
3
4
const Foo = require('./foo');
const Bar = require('./bar');
const someBarInstance = new Bar('John');
const someFooInstance = new Foo('Walter');

References