I have a JS Class and would like to be able to "reuse" it without running the constructor multiple times when I create the same classe with identical parameters.
The use case is for example a connection creation to a database that can be called from multiple functions at the same time and that may take a while to establish. For example, function1 in on part of the code calls MyClass(‘url1’) and function2 somewhere else calls MyClass(‘url1’) at the same time. I want to be able to avoid creating 2 connections to the database, while still be able to create MyClass(‘url22222’).
The class looks like:
class MyClass {
constructor(url) {
this.url = url;
console.log("Constructing MyClass with", url);
}
}
new MyClass("url1");
new MyClass("url1");
new MyClass("url22222");
Currently the output looks like:
Constructing MyClass with url1
Constructing MyClass with url1
Constructing MyClass with url22222
The goal is to have an output like:
Constructing MyClass with url1
Constructing MyClass with url22222
Thanks for your help !
I tried to store which url where created in an outside array but it does not look very pretty.
Also had a look at static initializer but it only run once per class regardless of the arguments provided as far as I understand.
2
Answers
A constructor can return an object other than the automatically-created object that is courtesy of
new
. Thus you can retain instances in some kind of cache, and use the URL as the key.If you want to avoid throwing away the object created by
new
(which in your case doesn’t seem like it’d be worth the trouble), you’d have to make some kind of static factory method to do what you want.If you are OK with
Proxy
, you could create a generic factory function for such cases and use it with any number of classes: