简体   繁体   中英

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?

 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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM