Skip to content

OOP in Javascript

Defining Classes

Classes in Javascript are simple to define, see the following

class TestClass 
{
    constructor(input, test) 
    {
        this.input = input;
        this.test = test;
    }

    doSomething()
    {
        // ...
    }

    getInput() {
        return this.input;
    }

    static getNewTest()
    {
        return new TestClass("a", 5);
    }
}

Similarities when comparing to PHP

Static Methods

Like PHP, there are static methods that we can call directly on the class itself.

let myClass = TestClass.getInput();

One class per file

While it is possible to have multiple classes in a Javascript source file, it is recommended to stick to one class per file.

Differences when comparing with PHP

No namespaces

Classes/functions do not have the concept of namespacing, this is instead handled by the module system using import and export.

No class properties

There is no concept of class properties (or "fields"). There is no way to define these values or their types before hand.

At the time of writing, there is an experimental feature in JS that enables this but browser support is limited and will need transpiling.

Properties are public

All properties that we set on the instance will be publicly accessible, Javascript does not use private or protected. Think of the the properties as public at all times.

No type hinting

There is no type hinting system in Javascript, you will have to check the data types being sent through and handle them accordingly.

Exporting and importing classes

Before a class can be used in another Javascript file, it needs to be imported using the module system.

To make a class reusable we first need to ensure we export it correctly. For single class files this is simple to do.

export default class TestClass
{
    // ...
}

We can then import it in another file and use the class by importing the class from the file we defined it in.

import TestClass from "the/file/name.js";

export default class SecondClass {
    constructor()
    {
        this.testClass = new TestClass("a", 1);
    }
}

More Information