Learning JavaScript ES6: Part 5: Classes

Learning JavaScript ES6

JavaScript ES6 (ECMAScript 6) is a newer specification for JavaScript introduced in 2015 and adopted by most browsers starting in mid-2016. It added new syntax and a greater ability to use object-oriented programming in JavaScript.


Classes

Previous to ES6, JavaScript was never quite an object-oriented programming language. It had many features that could be used in OOP ways to make objects and different approaches to extending object had been developed. Starting ES6, JavaScript moved even closer through two important new keywords: class and extends.

Previously, to create new objects, the new keyword was used to create a copy of an existing object. Using different approaches, it could be used as a new value based on the previous object.

The keyword class finally allows JavaScript to describe its own objects.

Constructors

Along with class, ES6 also introduced constructors to JavaScript. Previously, these were functions that acted in this role but did not have the specific name. Now, the keyword constructor can be used within a class to define what should happen when a new object is created.

Within ES6 JavaScript, constructors functions also serve as a good location to create internal variables and set initial values using default parameter values as well.

Get and Set

Adding even more object-oriented functionality, ES6 also added get and set functions. These can act as a quick shorthand for properties of an object to change or return a specific or calculated value.

Now, instead of writing functions such as getX() or getY(), the shorthand get and set forms can be used.

The use of get and set, however, come with a small caveat: they override existing property names. Any existing property names with the same names as the get and set usage will produce an error.

Play with the example on Repl.it!