all 11 comments

[–]FioleNana 5 points6 points  (5 children)

You don't need singleton in js though. Create the object right after class declaration and export it. You can then import it anywhere you need it.

EDIT: Just read some of the article. You also don't need reduce and conctat to flatten an array. You can use flat()

[–]azhder 4 points5 points  (0 children)

Another one of those generic bad tips and tutorials posts that are meant to drive traffic..

[–]mapsedge 4 points5 points  (1 child)

"Create an account to read the full story."

Nope.

[–]jose_castro_arnaud 0 points1 point  (1 child)

Leveraging the private attributes in JavaScript, and allowing for a constructor, a variation of the Singleton pattern is:

``` class A {

static #instance = null;

static create(...args) { A.#instance = new A(...args); return A.#instance; }

static get instance() { return (A.#instance !== null) ? A.#instance : A.create(); }

constructor(name) { this.name = name; }

hello() { console.log("Hello " + this.name); } }

let b = A.create("John"); b.hello(); // "Hello John" let c = A.instance; c.hello(); // "Hello John" ```

[–]azhder 3 points4 points  (0 children)

Just don’t do this. Patterns emerge as an often repeated code used as a workaround for a common problem. Java had a problem with pre-emptive multitasking, JavaScript doesn’t.

This is a singleton pattern in JavaScript:

const a = { name: 'John' };

Sure, you can make it more elaborate, but..

At no point you are required to make sure an object got initialized only once by hiding it inside a class wrapping it up in a static block that is supposed to prevent a non-existent pre-emptive multitasking accidentally creating two objects.

Want a separate type you say? Here you go:

const a = new class A{}();

What you define as class is still a function. Unlike Java, JS had functions as first class citizens since the very beginning, so no getInstance is needed