【问题标题】:Unable to call class methods inside its constructor无法在其构造函数中调用类方法
【发布时间】:2023-01-27 19:06:45
【问题描述】:

我正在努力实现我的 express 路由器(实际上这是我的主路由器的“子路由器”,这就是我必须扩展 express.Router 的原因)

我有以下代码(作为示例,我将其简化为只有一种方法):

import express from "express";

export default class MandatoryFieldsSettingsRouter extends express.Router {

    constructor() {
        super();

        this.get('/', this.retrieveMandatoryFieldsSettings);
    }

    async retrieveMandatoryFieldsSettings(req, res) {
        //some treatment here
    }
}

所以在创建应用程序主路由器的文件中,我可以像这样定义我的子路径:

router.use('/mandatory-fields-settings', new MandatoryFieldsSettingsRouter());

我在应用程序启动时出现以下错误 Error: Route.get() requires a callback function but got a [object Undefined],因为 this.retrieveMandatoryFieldsSettings 在构造函数中未定义。

我使用这个不同的方法声明修复了它:

    // 1st impl : this one is the "wrong" one causing my error
    async retrieveMandatoryFieldsSettings(req, res) {
        //some treatment here
    }

    // 2nd impl : this one is the "good" one making my application working
    retrieveMandatoryFieldsSettings = async function (req, res) {
        //some treatment here
    }

出于某种原因,我的公司希望我使用第一个实现。有什么方法可以使用它并保持我在构造函数中声明路径的方式吗? (我认为通过查看其构造函数来查看当前类中声明的每个路径更具可读性)。

我的公司并不封闭,如果绝对没有理由“禁止”第二次实施,请告诉我,如果您知道请解释两者之间的区别(-> 为什么第一个未定义而第二个没有? )

谢谢 !

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    如果您对私有成员 (#) 使用 ES2020 语法,则可以使用第一种方法:

    async #retrieveMandatoryFieldsSettings(req, res) {
        //some treatment here
    }
    

    问候, 克雷格

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 2011-06-19
      相关资源
      最近更新 更多