Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript ES6:ES6类中的分组方法?_Javascript_Class_Constructor_Ecmascript 6 - Fatal编程技术网

JavaScript ES6:ES6类中的分组方法?

JavaScript ES6:ES6类中的分组方法?,javascript,class,constructor,ecmascript-6,Javascript,Class,Constructor,Ecmascript 6,我们中的一些人正在尝试创建一个JavaScript库,以便在RESTful API上快速运行JSON查询 我想做的是根据它们的目的对一组方法进行分组 比如, 通过API,我能够获得用户属性。我不想将所有这些方法都放在主对象下,而是将它们分组到API类对象中 i、 e。 将此转换为: myAPI.getUserById() 为此: myAPI.User.getByID() myAPI.User.getByName() 我们将使用下面的代码作为一个简单的示例。如何将我的用户方法嵌套在myAPI

我们中的一些人正在尝试创建一个JavaScript库,以便在RESTful API上快速运行JSON查询

我想做的是根据它们的目的对一组方法进行分组

比如,

通过API,我能够获得用户属性。我不想将所有这些方法都放在主对象下,而是将它们分组到API类对象中

i、 e。 将此转换为:

myAPI.getUserById()
为此:

myAPI.User.getByID()

myAPI.User.getByName()
我们将使用下面的代码作为一个简单的示例。如何将我的用户方法嵌套在myAPI类中的用户对象中

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

    //Code to connect to instance...

  }

  getUserById(userId){
    // function
  }
}
已解决

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;
  }
}

你可以使用构图:

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

这样,您可以将所有类型的组划分为类。您甚至可以根据用户的需求区分不同的API实现。

这是许多应用程序使用的服务/模型模式的基础。谢谢Tim。从来没有这样想过。正是我想要的。非常感谢。我在JSFIDLE中添加了一个可能重复的示例-不,只使用一个类并没有很好的方法。