#Objects for functions on a class?

14 messages · Page 1 of 1 (latest)

zealous helm
#

Hey there, I am working on a class and want to be able to categorize functions through objects. For example:

const client = new Client();
client.economy.transactions();

What would be the best way to implement this?

I have tried the following:

class Client {
  public economy = {
    transactions: () => {
      // doing stuff here, in my use case I'd need `this` in here, so that's why the arrow function.
    }
  }
}

But that comes with two (or at least one) catch(es):

  1. In my use case, I'd need to be able to use overloading on functions like transactions, which I can't , since this has to be an arrow function to have this.
  2. From what I read online, this being a property instead of a method directly on the class (and its prototype) is a problem, not entirely sure about why.

Does anyone know of any better way to implement this?

wary shell
#

proxy, perhaps, that might be able to do something; that seems like more effort than it's worth though

zealous helm
#

Could you elaborate on what you mean?

wary shell
#

there's a Proxy thing that basically acts as a proxy for member accesses

#

i don't really know much about it, sorry

#

just that it exists

zealous helm
#

Hm yeah that does seem a bit complicated. But I know that what I want to achieve should be possible. I've seen API clients using syntax like this to mimic the API routes in the past. Just can't remember any specific one unfortunately.

But for example that /some/api/route would be .some.api.route()

wary shell
#

about 2: when you call a method, the instance itself is checked, then its prototype is checked for the function.
method declarations are attached to the prototype, while member declarations are attached to the instance
so members need to be redefined for each instance, taking some amount of memory for each instance.

#

you could have a static object that you then attach to the instance in the constructor maybe, to get around this

zealous helm
#

Well in my use case I'd only have one instance at a time usually so that wouldn't be a problem then, would it?

wary shell
#

yeah

#

if it's a singleton, why have it be a class at all here btw?

zealous helm
#

Well, the focus lies on usually.
The library exposes a getClient() function which returns the client instance if one is present or creates an instance if none is present.
I also expose the Client class directly to give the user the flexibility to theoretically create multiple instances for whatever reason.

wary shell
#

mm i'd say to support that latter case