Quick JavaScript OOP


Defining a class

class Employee {

}

Defining the constructor

class Employee {
    constructor () {
    }
}

Adding properties

class Employee {
    constructor (name, salary) {
        this._name = name;
        this._salary = salary;
        this.bonus = 1.05;
    }
}

Creating a method

class Employee {
    constructor (name, salary) {
        this._name = name;
        this._salary = salary;
        this.bonus = 1.05;
    }
    calculatePayment () {
        return this._salary * this.bonus;
    }
}

Static properties

class Employee {
    static counter = 0;

    constructor (name, salary) {
        this._name = name;
        this._salary = salary;
        this.bonus = 1.05;

        Employee.counter += 1;
    }
    calculatePayment () {
        return this._salary * this.bonus;
    }
}

Getters and setters

class Employee {
    static counter = 0;

    constructor (name, salary) {
        this._name = name;
        this._salary = salary;
        this.bonus = 1.05;

        Employee.counter += 1;
    }
    calculatePayment () {
        return this._salary * this.bonus;
    }
    get name () {
        return this._name;
    }
    set name (novoNome) {
        this._name = novoNome;
    }
}

Inheritance

class Manager extends Employee {
    constructor (name, salary) {
        super(name, salary);
        this.bonus = 1.07;
    }
}
class Diretor extends Employee {
    constructor (name, salary) {
        super(name, salary);
        this.bonus = 1.09;
    }
}

Overwrite method

class Diretor extends Employee {
    constructor (name, salary) {
        super(name, salary);
        this.bonus = 1.09;
    }
    calculatePayment (additional=0) {
        return super.calculatePayment() + additional;
    }
}

Simulate abstract class

class MyClass {
    constructor () {
        if (this.constructor === MyClass) {
            throw new Error('"MyClass" is abstract');
        }
    }
}

Simulate abstract method

class MyClass {
    constructor () {
        if (this.constructor === MyClass) {
            throw new Error('"MyClass" is abstract');
        }
    }
    meuMetodo () {
        throw new Error('Not implemented');
    }
}

References