javascript - 在 JavaScript 类中使用命名空间

标签 javascript class namespaces

我正在为 RESTful API 构建客户端,在 API 中有一些具有相同功能的模块,例如 GetVersion将返回特定模块的版本。

https://example.com/core/GetVersion -> 1.1
https://example.com/auth/GetVersion -> 1.8
有多个具有相同功能/端点的模块。
我想知道如何将它实现到我正在构建的 API 类中,
我尝试将模块的所有函数都输入到命名空间中,但是这些函数无法访问命名空间之外的方法和属性。
class API {
    constructor(config) {
        this.user_id = config.user_id
        this.password = config.password
        this.basePath = `https://${config.server}/`
        this.instance = axios.create({
            httpsAgent: new https.Agent({
                rejectUnauthorized: false
            })
        });
        this.authToken = undefined
    }

    /******************/
    /* Helper Methods */
    /******************/

    request(endpoint, body, config) {
        const url = this.basePath + endpoint
        config.headers = {
            "Accept": "application/json"
        }

        // all requests are POST requests
        return this.instance.post(url, body, config)
            .then(res => {
                return res.data
            })
            .catch(function (error) {
                console.error(error);
            });
    }


    /*****************/
    /* Core Services */
    /*****************/
    core = {
        getVersion() {
            return this.request('core-service/getVersion', {}, {}).then(res => {
                console.log(res)
            })
        }
    }


    /*****************/
    /* Auth Services */
    /*****************/
    auth = {
        getVersion() {
            return this.request('auth-service/getVersion', {}, {}).then(res => {
                console.log(res)
            })
        }
    }

}

const api_client = new API({
    user_id: 'admin',
    password: 'admin',
    server: 'example.com'
})

api_client.core.getVersion()
api_client.auth.getVersion()
但我得到了错误
return this.request('core-service/getVersion', {}, {}).then(res => {
            ^
TypeError: this.request is not a function
为了在同一个类中获得不同的命名空间,使用的最佳实践是什么?

最佳答案

我将命名空间中的方法更改为

getVersion: () => {***}
现在可以使用了。

关于javascript - 在 JavaScript 类中使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68441843/

相关文章:

javascript临界区或信号量问题

javascript - JS : Loop forces ascending sorting, 如何保持定义的顺序?

javascript - .map() 中的 If 语句?

java - 类初始化是否检查其成员方法?

php - 如何在 Symfony Bundle 中包含自定义类?

用于多用户应用程序的 mongodb 数据库架构

javascript - 如何使用 jQuery 的 attr 方法设置 "style=display:none;"?

PHP:php 找不到 include() 脚本中定义的类

c++ - 在 C++ 中的运行时声明对命名空间的引用

MongoDB CREATE SCHEMA 等价物