How to use Javascript classes

19 Nov 20206 min read

Javascript classes have always been quite different from classes that are available in other strongly-typed Object Oriented programming languages like Java, C#, C++ etc.

There are some syntactic similarities, and it is possible to emulate many of the features of classical classes in Javascript, but it is best to understand that Javascript's classes and prototype-based inheritance mechanism are substantially different from the classes and class-based inheritance in other object oriented programming languages.

The ECMAScript 2015 Language Specification introduced syntax element and provided constructors , static, instance methods, inheritance and the ability to extend a class from other classes.

The class syntax, is just syntactic sugar concealing Javascript prototypal inheritance.

Syntactic sugar is a term for syntax changes in computer programming which make it easier for humans to code.

What is prototypal inheritance

Javascript's fundamental data type is the object. An object is a composite value enabling aggregation of multiple values and storing and retrieval of values by name. An object is an unordered collection of properties each of which has a name and a value.

Property names are strings, which at a most basic level enable the mapping of strings to values. However, in Javascript an object is more than sa simple string to value map, it can also maintain its own set of properties and call also inherit properties of another object, known as a prototype.

The methods of an object are typically inherited properties and this Prototypal Inheritance is a key feature of Javascript.

prototypical inheritance refers to the ability to access object properties from another object.

In older versions of Javascript an object's class attribute is string that provides information about the type of object. However, there was no way of setting this attribute and there was only indirect technique for querying it. The code below would return the type of class that an object has been defined as.

function classof(o) {
  if (o === null) return "Null";
  if (o === undefined ) return "Undefined";
  return Object.prototype.toString.call(o).slice(8, -1);
}

What is a class

A class is blueprint for any number of objects. A class describes the type of an object - how it is represented and what operations can be carried out on it.

The conventional wisdom in programming is that classes should be small, not deep.

A class should contain exact specifications on what can be done with an object. The specification is the class' contract.

Defining classes in Javascript

ES 2015 introduced a special keyword class which we can use to define a class.

class SomeCoolClass {
   // The body of the class
}

The code above defines a class SomeCoolClass. The braces { } delimit the class body. This is an example of the class declaration syntax.

What would Javascript be, if there weren't alternative approaches of achieving the same thing. You can also define a class by making use of the class expression to assign a class to a variable.

const SomeCoolClass = class {
  // The body of the class
}

You can also export a class as part of ES2015 module, making use of the default export syntax

export default class SomeCoolClass{
 // The body of the class
}

The exact same thing can be achieved making use of the named export

export class SomeCoolClass {
// The body of the class
}
Class Name Convention

It is generally accepted naming convention within the Javascript community to name classes using Pascal Case in contrast to other Javascript data structures.

Constructor

The constructor method is a unique method for creating and initializing the object created with the class. There can only be one unique method with the name “constructor” in a class. The constructor can use the super keyword to call the constructor of the superclass, which is the constructor of the class you are deriving your class from.

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

constructor(param1, param2, ...) is a special method in the body of a class that is used to initialize an instance of a class. It's typically the place where one would set the initial values for the fields, or do any kind of object setup.

In the example below we will add a constructor method to our class which will accept an argument for a name value we can add to help describe our class.

We can then initialise an instance of our class can provide some catchy name.

class SomeCoolClass {
   
  constructor(name) {
    this.name = name;
  }
}

const someClass = new SomeCoolClass('A cool class  name');

If you don’t define a constructor method for a class, a default one is created. The default constructor is an empty function, which doesn’t modify the instance.

class SomeCoolClass {
   
  constructor() {}
}

Classes can extend - a.k.a inherit, other classes , therefore if your class is derived class, the default constructor calls the parent constructor, passing alon any arguments that were provided.

constructor(...args) {
 super(...args);
}

This enables the code to function as follows.

class SomeCoolClass {
   
  constructor(name) {
    this.name = name;
  }
}

class InheritedCoolClass extends SomeCoolClass {
 
       printClassName() {
        return this.name;
    }
}
 
   
    let cool = new InheritedCoolClass("Kajagoogoo")
    console.log(`My class name is : ${ cool.printClassName() }`)
}

Fields

Class fields are variables that hold information. Fields can be attached to 2 entities:

  • Fields on the class instance
  • Fields on the class itself (aka static)

The fields also have 2 levels of accessibility:

  • Public: accessible anywhere
  • Private: accessible only within the body of the class

Public Instance Fields

In the code above we created a public instance field in the constructor name, we could access this field outside of the class as follows

const someClass = new SomeCoolClass('A cool class  name');
console.log(someClass.name);    // Would print out A cool class  name to the console

The downside to creating implicitly inside the constructor, as above, is it could be difficult for other developers to understand and grasp the fields list, because they would have to decipher them from the constructor’s code.

A better approach would be to explicitly declare the class fields. Therefore, irrespective of the constructor, the instance always has the same set of fields.

We can declare a name; field inside the body of the class which declares a public field name.

The public fields declared such a way is expressive and ensures the fields exist on every created instance of the class. This ensures the field is always present and assists in ensuring the class definition is more self-documenting.

Public instance fields are added with Object.defineProperty() either at construction time in the base class or just after super() returns in a subclass.

a quick look at the fields declarations is enough to understand the class’s data structure.

class SomeCoolClass {
   name;   

 constructor(name) {
   this.name = name;
 }
}

There is no restriction on access or update of the public fields. Developers can read and assign values to public fields inside the constructor, methods, and outside of the class.

Private instance fields

Developing Javascript you will often need encapsulate the inner workings or your class from the outside. Using encapsulation the public interface of the class provides does not couple it to the implementation details of the class.

encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components

To declare private fields in Javascript classes we only need to prefix the name with a # symbol. The prefix should be used everytime you declare and reference the field.

class SomeCoolClass {
   #name;   

 constructor(name) {
   this.#name = name;
 }
}

The #name is a private field and can only be accessed and modified within the body of the class. If we try access the name field in code now, we will now be thrown an error.

Public Static Fields

Static fields are helpful to define class constants or store information specific to the class. This is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

To create static fields use the special keyword static followed by the field name: static coolStaticField.

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

© 2019 - 2020 Geek.I.Am All Rights Reserved.