Introduction

In this blog article, we shall learn about Classes introduced in ES6. Classes are blueprints for creating objects.

It’s worth noting that JavaScript has no classes. What appear to be classes is a syntactical sugar for the prototype-based Object-Oriented mechanism of JavaScript.

Classes

Classes enable us to model a problem. We add fields and methods to alter these fields when the object is in use. ES6 are do not fully look like classes in other classes. Fields and methods do not have access modifiers that guard access to these fields. private, public, protected keywords do not exist.

Interfaces and abstract classes do not exist too.

class User {
  name
  age
  constructor(_name, _age) {
    this.name = _name
    this.age = _age
  }

  // some possible code here
}


const user = User('Anita', 20)
user.name = 'Cindy' // all fields are open to modificaton

Coming from a language such as C# or Java it’s good to note that ES6 classes work differently as normal classes due to the issues discussed above.

Setters & Getters

Class implementation provide getters to set values of fields and get values off the fields of an object

Inheritance

A class can inherit from a parent class and have access to the fields and methods of that class.

class Animal {
  move() {
    console.log('animal moved...')
  }
}

class Cow extends Animal {
  // possible code here
}

const cow = new Cow()
cow.move()

Class Methods

A class method can be call on the instance of that class (object construced using new ClassName(args) { } syntax) as shown in the trivial example below:

class Animal {
  move () {
    console.log('animal moved...')
  }
}
const animal = new Animal()
animal.move() // prints animal moved...

Summary

Due to the confusing nature of ES6 classes, most codebases use composable functions organized into reusable modules