'Initiate single instance from a constructor and use it as static method in another class

I have a class of utilities that I use all over my app it contains a method to format numbers

class Utils {
    static numberFormater () {
        return new Intl.NumberFormat('en-US')
    }
}

the problem is whenever I call it it will return new numberFormat instance (which affects the performance of the code)

I want to make one instance and use it whenever I call this method



Solution 1:[1]

Why not simply create an instance of the number formatter directly? Doesn't even need to be a static property:

class Util {
  constructor () {
    this.numberFormatter = new Intl.NumberFormat('en-US');
  }
}

const util = new Util;

const formatter1 = util.numberFormatter;
const formatter2 = util.numberFormatter;

console.log(formatter1 === formatter2);

Solution 2:[2]

Try adding a constructor which initializes the numberFormater.

class Util {
  constructor(locale) {
    this.numberFormater = new Intl.NumberFormat(locale);
  }
  static numberFormater() {
    return this.numberFormatter;
  }
}

var a = new Util('en-US');
console.log(a.numberFormater.format);

Solution 3:[3]

If you want to make one instance and use it every time you can use a Singleton pattern.

The singleton design pattern solves problems like:

  1. How can it be ensured that a class has only one instance?
  2. How can the sole instance of a class be accessed easily?
  3. How can a class control its instantiation?
  4. How can the number of instances of a class be restricted?

More information on the pattern and javascript you can read:

  1. Singleton pattern in ES6
  2. Singleton pattern with example
  3. JavaScript Design Patterns: Singleton

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gian1200
Solution 2 Hodrobond
Solution 3 ????????? ???????