2

Hi I want to achieve something like this in TypeScript/JavaScript

const foo = new something();
foo.group.method();

I've already tried using objects and it works just fine but I was wonder is this the best way to achieve this or not
My Code:

class something{
    someMethod(){
       //do something
    } 
    group:{
       doSomething:()=>{
          //my grouped method
       }
    }

}

Shawn Vn
  • 297
  • 1
  • 14
  • Be careful though - `this` will be the group and not the class instance. – CherryDT Jul 30 '20 at 23:32
  • @CherryDT Yeah I know that and typeScript fixes this issue but do you think this is the best way ? – Shawn Vn Jul 30 '20 at 23:34
  • May I ask why you want to do that? Does it have a purpose beyond simply logical grouping of related methods? – see sharper Jul 31 '20 at 00:07
  • @seesharper I'm trying to develop a small library. I thought grouping related methods will make the documentation more understandable, and I've seen similar patterns in other frameworks or libraries so I decided to do this. – Shawn Vn Jul 31 '20 at 00:22

2 Answers2

1

If you must have the ability to call foo.group.method(), then you have no choice but to construct the group object with its associated methods when you create a something, most logically by doing so in something's constructor. There really isn't any alternative syntactical sugar to let you group methods without their sharing an object. Even typescript's namespaces (different use case but a similar intention of logical grouping) actually use objects under the hood, because that's all JavaScript has. I would suggest that if the purpose is only logical grouping, then you probably shouldn't do it, because it is unconventional and is probably creating more complication than it's worth, but of course your use case may dictate otherwise.

see sharper
  • 11,505
  • 8
  • 46
  • 65
  • Thanks for your answer can you suggest any alternative solutions then ? – Shawn Vn Jul 31 '20 at 00:24
  • 1
    As this is a library, you may want to structure things differently, but it is hard to recommend how without knowing any details. Typically with a library you are exposing a lot of functions - you don't necessarily want them all on a big class/object, which will need to be constructed, thus unnecessarily consuming memory. I'd suggest exposing an API of functions which take the class instance as an object parameter, but as I say, hard to know without the details. – see sharper Jul 31 '20 at 00:30
0

One way to do this would be to use modules and then set up module exports in a way that makes sense. Using CommonJS, it would be something like this:

someMethod() {}
doSomething() {}

module.exports = {
  someMethod,
  group: {
    doSomething
  }
}

Edit: Also, putting sub-classes as static properties might be something you're interested in.

tripathiakshit
  • 624
  • 5
  • 17