Jump to Categories

Classes

Classes, introduced in ES6, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance

An important difference between function and class declarations is that function declarations are hoisted and class declarations are not.

The constructor method is a special method for creating and initializing an object created with a class - there can only be one within a class.

// Class declaration
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

// Class expression
const a = class {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

Static methods

Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  static addAges(a, b) {
    return a + b;
  }
}

const p1 = new Person('Shane',33);
const p2 = new Point('Paul',34);

console.log(Person.addAges(p1, p2));

Super

Super() will call the constructor of its parent class. This is required when you need to access some variables from the parent class.

Super() must come before the this keyword as it it uninitialized if Super() is not called.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  testing() {
    console.log('yess');
  }
}
class Worker extends Person {
  constructor(name,age) {
    super(name,age); 
  }
  speak() {
    console.log(this.name);
  }
}

const a = new Worker('John', 21)
a.speak();

Refs