JavaScript: Classes

Creating Templates for Object Creation

Jake Mills
May 13 · 3 min read
Photo by Feliphe Schiarolli on Unsplash

It’s the third and final week/story covering the process of creating objects from functions. I first dove into the subject of factory functions and moved from that idea to constructor functions. All that was child’s play until this point; now we’re playing in the big leagues—JavaScript classes.

JavaScript classes are essentially syntactic sugar of the prior two methods I previously discussed. Classes accomplish the very same thing, a function returning an object, but in a more pleasing, easily consumable way. Before, we would have to build the constructor function and define different methods it could access via the prototype chain separately. With classes, we can keep all of it in one place.

Our Hero constructor function from before. We can do better!

Classes

To start building a class in JavaScript, you need to begin with the keyword class. So, if we were to begin building our Hero template, we would write:

class Hero {}

Simple enough. From here, we now need to add the unique properties we will define on each instantiation of our class. If you looked at my previous article about constructor functions, this will look somewhat familiar to you.

class Hero {
constructor(name, alias, abilities) {
this.name = name;
this.alias = alias;
this.abilities = abilities;
}
}

This ‘special function’ looks very similar to how we defined our Constructor functions before. Each class, when defined, needs to contain this unique constructor method. It can only have one constructor method in the class; otherwise, a SyntaxError will be thrown. For funsies, why don’t we add a console.log to see what happens within this constructor function!

class Hero {
constructor(name, alias, abilities) {
console.log('THIS IS THE BEGINNING OF CONSTRUCTOR');
this.name = name;
this.alias = alias;
this.abilities = abilities;
console.log('THIS IS THE END OF CONSTRUCTOR');
}
}
let captainAmerica = new Hero('Steven Rogers', 'Captain America', ['Enhanced strength, speed, stamina, durability, agility, reflexes, senses, and mental processing via the super soldier serum', 'Master martial artist and hand-to-hand combatant', 'Accelerated healing', 'Immunity to diseases and toxins', 'Slowed aging', 'Master tactician, strategist, and field commander', 'Using Vibranium-steel alloy shield'])// I know that captainAmerica object looks terrible in the Medium code template, but what ya gonna do? //

If you run the code above in your browser, you’ll notice that the two strings print to the console right away when creating a new instance of the Hero class, meaning our constructor function is called immediately with the new creation. Furthermore, it sets the value of this to a new empty object and then adds the proper values to that object based upon the values we pass through upon creation thanks to the new keyword.

A couple of other things to note. When defining a new class, it is standard to start the definition with a capital letter (i.e. class Hero). Also, you can define the properties within the constructor method with different names, like this.alias = alias could be this.orange = alias, but, for what I think are obvious reasons, it is standard practice to do this.alias = alias.

Okay, but the real advantage of JS classes comes with methods. We don’t have to define them on the outside and add them to the prototype chain as we did with Constructor functions (Hero.prototype.assemble = function(){}). Classes provide that sweet, sweet syntactic sugar allowing us to do the following:

Boom! Doesn’t that look and feel nice? When we instantiate a new instance of our Hero class, these two methods (assemble & disassemble) are included automatically in the object’s prototype chain. It really is that simple.

Happy Coding 🤓

Geek Culture

Proud to geek out. Follow to join our +500K monthly readers.

Jake Mills

Written by

Software Engineer hailing from the Empire State, writing about what interests me and hoping someone else finds it interesting too. 👨🏻‍💻 🤓 He/Him #LFGM

Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Jake Mills

Written by

Software Engineer hailing from the Empire State, writing about what interests me and hoping someone else finds it interesting too. 👨🏻‍💻 🤓 He/Him #LFGM

Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store