spali
spali

Reputation: 13

How to access methods inside another classes through instance of another class in Javascript

I have two classes as follows.

class Users{
    createUser(){
       //...
    }
}

Another class

class Cars{
    createCar(){
       //....
    }
}

Main class

class Api{
    //....
}

I need to access the first two classes though last class as follows

Api=new API()
Api.Users.createUser()
//also
Api.Cars.createCar()

How it is possible in javascript. is this a good practice?

Upvotes: 0

Views: 615

Answers (2)

Mischa
Mischa

Reputation: 1601

class Users {
    createUser(){
       console.log('createUser');
    }
}

class Cars {
    createCar(){
       console.log('createCar')
    }
}

class Api  {
    Users = new Users;
    Cars = new Cars;
}

var api = new Api()
api.Users.createUser()
api.Cars.createCar()

Upvotes: 3

Chris L
Chris L

Reputation: 129

You will need to create an instance of each class inside the API class. Then you can access them through dot notation and call their respective public functions.

Upvotes: 0

Related Questions