【问题标题】:Using namespaces inside JavaScript Class在 JavaScript 类中使用命名空间
【发布时间】:2021-09-27 04:43:27
【问题描述】:

我正在为一个 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

为了在同一个类中获得不同的命名空间,最佳实践是什么?

【问题讨论】:

标签: javascript class namespaces


【解决方案1】:

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

getVersion: () => {***}

现在可以使用了。

【讨论】:

  • 请注意,这些方法仅在使用new 实例化对象时存在。它们不会存在于原型中。
猜你喜欢
  • 1970-01-01
  • 2013-02-13
  • 2012-11-06
  • 1970-01-01
  • 2014-10-17
  • 2018-05-29
  • 2010-12-05
  • 2011-12-02
  • 2011-03-25
相关资源
最近更新 更多