0

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?

spali
  • 13
  • 5
  • Use dependency injection, `class Api { constructor(users, cars) { this.users = users, this.cars = cars } }` and `Api = new Api(new User, new Car)`. – eMontielG Mar 06 '20 at 12:39
  • Possible duplicate of [this question](https://stackoverflow.com/questions/39175922/how-to-access-a-method-from-a-class-from-another-class) – Aman Verma Mar 06 '20 at 12:40

2 Answers2

3

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()
Mischa
  • 1,591
  • 9
  • 14
0

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.

Chris L
  • 129
  • 5