elias91 elias91 - 7 months ago 15
Javascript Question

JavaScript ES6: Grouping methods in es6 classes?

A few of us are trying to create a JavaScript library to quickly run JSON queries on a RESTful API.

What I'd like to do is group a set of methods relative to their purpose.

For example;

Through the API I am able to get user attributes. Instead of having all of these methods under the main object, I'd like to group them within the API class object.

i.e.
Transform this:

myAPI.getUserById()


To This:

myAPI.User.getByID()

myAPI.User.getByName()


We'll use the code below as a simple example. How might I have my User methods nested within a User Object within myAPI Class??

class myAPI {
constructor(url) {
this.url = url;

//Code to connect to instance...

}

getUserById(userId){
// function
}
}


Solved

class myAPI {
constructor(url) {
this.url = url;
this.UserAPI = new UserClass(this);

//Code to connect to instance...

}

getUserById(userId){
// function
}
}

class UserClass {
constructor(parent){
this.myAPI = parent;
}
}

Tim Tim
Answer

You could use composition:

class UserAPI {

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

    getById() {
    }
}

class API {

    constructor(url) {

        this.url = url;
        this.User = new UserAPI(url);
    }
}

var myAPI = new API();

myAPI.User.getById();

This way, you can separate all kind of groups into classes. You can even discriminate different implementations of API's based on the user's requirements.

Comments