If you come from Java or C++ background, you are probably used to classic OOP model, and it is hard to imagine how you can implement singleton in J...
For further actions, you may consider blocking this person and/or reporting abuse
This can also be done in ES6 like so:
Yes, this is another way of doing it.
Not sure this is a Singleton at all, just an immutable instance due to a closure creating pseudo-private members.
A Singleton indicates you can only ever have one instance of an object. Every
new Http(args)
would be a reference to the same thing.This assumption is correct. That said, you should not use
new
keyword with this pattern. You can add a function to explicitly initialize singleton, and it would look more like traditional "Java" singleton. I don't think the latter is necessary though.Good article! I reproduced it using ES6 modules:
Cool! Glad you like it, and thanks for ES6 example!
Can you explain this to a 5 year old?
If the 5 year old already has some experience with programming, then it may work:
One way to implement singleton pattern in JS, is to encapsulate (enclose) desired members into outer function, but provide reference to desired properties of these members using inner function (same scope as the members). We can then immediately execute (invoke) inner function, and assign the value to a variable in a global scope (or different scope depending on use).
Thank you,
From a 6 year old.
What about this approach?
class SomeClass {
constructor() {
if (!SomeClass.instance) {
SomeClass.instance = this;
}
}
}
Yes, this is another way of doing it. More OOP way, I would say.