Another fantastic feature that ES6 offers is the ability to create classes within JavaScript, technically, Classes were introduced in ES5 and were introduced to make it easier to use JavaScript already existing ‘prototype-based inheritance mechanism. However, this may have been introduced but it is not 100% object oriented, as they are in fact special functions. If you were to enter the below code in an online editor and console.log the response you will see the type the class is defined as is a function.
class Test{
}console.log(typeof(Test))
You can define a class by either a “class declaration” or a “class expression”.
Class declaration
To declare a class you can use the keyword “Class” and then enter the name you wish to give to the class and a pair of curly braces like the below.
class Person{
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;}
Class expression
To declare a class expression you will need to assign the class to a variable using var, let or const like the below. If you choose to use class expressions you will be able to use the class name inside of the class itself.
let Person = class Person2{ constructor(firstName,lastName){ this.firstName = firstName;this.lastName = lastName;}}
In addition, the class expressions do not have to be named classes either as seen below. You can also figure out the name that has been given to the class expression by using the name property and invocating it on the variable itself and not an instance of the class.
let Person = class {
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
sayHello(){
console.log('hello ' + this.firstName + ' ' + this.lastName)
}
}
var Alex = new Person('Alex','test')console.log(Alex.sayHello())
console.log(Person.name)
Constructor
The purpose of the constructor method is to create and initialize an object of the instantiated class, this may also include assigning instance properties inside of the constructor to arguments on the class after you instantiated the class. You are only allowed one “constructor” method inside each class.
Defining methods
Like in other languages such as C#, JavaScript classes allow you to use “getters” and “setters” to read and write properties from the class. An example of this below where I have made an instance of the “Person” class and placed one argument of “Alex”.
class Person {constructor(firstName) {
this._firstName = firstName
}
get name() {
return 'my name is: ' + this._firstName
}set name(newFirstName) {
this._firstName = newFirstName
}
}let myName = new Person('Alex')
console.log(myName.name)myName.name = 'Jack'
console.log(myName._firstName)
Inside of the constructor the “_firstName” property is equal to what has been set in the “firstName” argument of the constructor.
We can then use the “name” “get” property accessor to retrieve the “_firstName” property of the class and as we can see it returned “Alex”, however we can also change that by using the variable which contains the instance of the class which is “myName” and using it to run the “set” property called “name” and pass an argument of your choice to this property, this then sets the “_firstName” property equal to whatever value was inputted as an argument and for this case we can see it is Jack. So for this class instance we can see the “_firstName” property is now Jack.
Static methods
Within JavaScript classes you can also create static methods, static methods are ran/called without creating an instance of your class so cannot be run on an instance of a class so this is a use case for creating a static method. A popular use case (one that I have found in my experience anyway) of static methods is to create them when you want to build a helper utility for your projects i.e. you may want to build a helper file that performs calculations or conversions on specific sets of data and instead of writing multiple lines of code each time you do this calculation you write a static helper method once and then call it each time you require it.
class Person {constructor(firstName) {
this._firstName = firstName
}
get name() {
return 'my name is: ' + this._firstName
}set name(newFirstName) {
this._firstName = newFirstName
}
static testStaticMethod(){
return 'this is a static method!'
}
} let myName = new Person('Alex')
console.log(Person.testStaticMethod())
console.log(myName.testStaticMethod())
When i run “myName.testStaticMethod()” you will see in the console that an error appears, this is because I am trying to run a static method on an instance of a class which is incorrect.
Extends
The keyword extends is used to create a class as a child of a parent class. I have created a parent class of “Animal” with 2 instance properties, name and species, in addition, I have added 2 methods, one of them being “saySpecies”. Furthermore, I have created another class called “Snake” which uses the “extends” keyword to inherit the properties and method of the class “Animal”. In the class “Snake” I have overwritten the method “saySpecies” to return a console.log that contains the value I have set for the “_species” property. Below is an example of this.
class Animal{
constructor(species,name){
this._species = species;
this.name = name;
}
saySpecies(){
console.log(this._species)
}
sayName(){
console.log(this_name)
}
}class Snake extends Animal{
constructor(species){
super(species);
}
saySpecies(){
console.log(' i am snake and i am part of the ' + this._species + ' species')
}
}let rattleSnake = new Snake('Rattlesnake')
rattleSnake.saySpecies()
Hoisting
One of the major distinctions between functions and classes is that functions (declarations) are hoisted meaning that you do not need to declare your function first and then access it, however, with classes you need to declare your class first and then access it otherwise an error will occur. So when you are creating a class declaration you are not allowed to do the following.
var s = new Snake();class Snake {}
I hope you have learned something about ES6 classes in JavaScript from this article, again if you have any feedback or constructive criticism please feel free to respond or tell me on my twitter.
Thanks again for reading a clap or a share is always appreciated, have a great day!