简体   繁体   English

如何通过Javascript中另一个类的实例访问另一个类中的方法

[英]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.在 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.您需要在 API 类中创建每个类的实例。 Then you can access them through dot notation and call their respective public functions.然后你可以通过点符号访问它们并调用它们各自的公共函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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