How to Use Singletons and Decorators in Object-Oriented JavaScript?

Estimated read time 1 min read

Singletons and decorators are advanced concepts in object-oriented programming that can be used in JavaScript.

Singletons: A singleton is an object which only has one instance across the application. This can be implemented in JavaScript by creating a class with a static method that returns the same instance every time it is called.

Example:

class Logger {
  static instance;
  constructor() {
    if (!Logger.instance) {
      Logger.instance = this;
    }
    return Logger.instance;
  }
}

const log1 = new Logger();
const log2 = new Logger();
console.log(log1 === log2); // true

Decorators: A decorator is a design pattern in object-oriented programming that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. In JavaScript, this can be implemented using the @ symbol, followed by the name of the decorator.

Example:

function readonly(target, name, descriptor) {
  descriptor.writable = false;
  return descriptor;
}

class Point {
  @readonly
  x = 0;
  y = 0;
}

const p = new Point();
p.x = 1; // error

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply