ES6 Classes, when to use them & how they work

My team and I had a discussion about the use of classes within our applications. There were some concerns about them being used as if they were Java classes (think StrategyIteratorDescriptorAdapterOrderBroadcaster). However, we came to the conclusion that there is a clear distinction between when to use them, and when not to.

When to use them

Our team came up with an interesting point: what’s the difference between a class and a function? In javascript, not a whole lot. However, when thinking about it in the broader sense, my teammate stated:

How classes work in Babel

Classes are simply syntactic sugar. Ultimately, when transpiled by Babel, the classes become simply functions.

class Test {  
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hi, ${this.name}.`);
}
}
new Test('Evan').sayHi();
function _classCallCheck(instance, Constructor) {  
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
var Test = function () {
function Test(name) {
_classCallCheck(this, Test);
this.name = name;
}
Test.prototype.sayHi = function sayHi() {
console.log('Hi, ' + this.name + '.');
};
return Test;
}();
new Test('Evan').sayHi();

Conclusion

Babel allows for us to utilize (what I consider) to be a very clean syntax. I will highlight this syntax in my next post in implementing classes in Angular (more specific examples). If you are interested in viewing a more in depth explanation of class features and syntax, check out the video below.

Front End Developer

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