Creating a Constructor Class in ES6

Scott Schaefer
Jul 25, 2017 · 2 min read

Everyone knows how to create a constructor, right? But maybe you’re not quite so familiar with how it’s done ES6 style.

If you wanted to populate the Earth with humans, you’d need to create TONS of humans. You would definitely need some machine that would produce FOR you. The first step to creating this machine is to utilize the class keyword:

class Human {}

This merely establishes the name of the class and that it is indeed a class. Next up you must add the class constructor function:

class Human {
constructor () {

}
}

This constructor function does exactly what it states, i.e. it constructs. Inside the constructor function you add whatever properties you want your human clone (more appropriately called Human instance) to have.

class Human {
constructor (name) {
this.eyes = true;
this.arms = 2;
this.legs = 2;
this.name = name;
}
}

Since the constructor now has properties, when you create an instance of Human (a clone) by running var scott = new Human('Scott'), it’s already populated with a few properties that are common to all your Human creations.

To take this one step further, let’s add a few methods to this Human creation machine.

class Human {
constructor (name) {
this.eyes = true;
this.stomach = 'empty';
this.arms = 2;
this.legs = 2;
this.name = name;
}
eat () {
this.stomach = 'full';
}
sleep () {
console.log('Zzzzzz');
}
}

These clones can now eat and sleep.

That’s really it. There isn’t any fiddling with different types of constructor patterns and such like that. It’s simply this.

Written by

Software Engineer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade