HomeAbout

Object Oriented Programming

Class

Code within the class body is always executed in strict mode.

Class is an uninstantiated state

The methods in class are not accessible unless it is instantiated.

What is a Constructor

If you don't define a constructor in a class, empty default constructor is provided.

// default and implicit constructor() {}

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

class Example { constructor(a, b) { this.a = a; this.b = b; } getSum() { return this.a + this.b } } const instantiatedExample = new Example(1, 2); instantiatedExample.getSum(); // 3

When to use constructor vs field property

Field property does not use variable declaration syntax.

  • Field property is set to undefined when default value is not provided.

Use field property when a default value should be common across all instances.

Use constructor when a property's value should vary between instances of a class.

class AnotherClass { constructor() {} // implicitly created when absent someProperty = "some property" // class field getSomeProperty() { return this.someProperty; } } const instantiatedAnotherClass = new AnotherClass(); instantiatedAnotherClass.someProperty; // 'some property' instantiatedAnotherClass.getSomeProperty; // fn getSomeProperty instantiatedAnotherClass.getSomeProperty(); // 'some property'

You technically "can" achieve the same effect with constructors:

class Person { constructor() { // Default values or optional initialization this.name = 'DefaultName'; this.age = 0; } sayHello() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } const person = new Person(); person.sayHello(); // Hello, my name is DefaultName and I am 0 years old.

Inheritance and role of super()

If your class is a derived class, the default constructor calls the parent constructor, passing any arguments that were provided:

// default constructor when no constructor is provided to the derived class constructor(...args) { super(...args); }
class ValidationError extends Error { printCustomerMessage() { return `Validation failed :-( (details: ${this.message})`; } } try { throw new ValidationError("Not a valid phone number"); } catch (error) { if (error instanceof ValidationError) { console.log(error.name); // This is Error instead of ValidationError! console.log(error.printCustomerMessage()); } else { console.log("Unknown error", error); throw error; } }

When a constructor is provided to a child class, you must call the parent class constructor explicitly using super().

Implications of using super()

When a method in a class uses a super(), it means the superclass of the current class has a equivalent method it inherits from.

So you need to understand what the parent’s method is doing before overriding or inheriting the behavior.

Static Methods

Static properties cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

class ClassWithStaticMethod { static staticProperty = "someValue"; static staticMethod() { return "static method has been called."; } static { console.log("Class static initialization block called"); } } console.log(ClassWithStaticMethod.staticProperty); // Expected output: "someValue" console.log(ClassWithStaticMethod.staticMethod()); // Expected output: "static method has been called."
AboutContact