javascript - NodeJS从子类访问父类构造函数中的对象
问题描述
我正在尝试创建一个控制器类,它将使用 ExpressJS 为我初始化所有路由这是我所拥有的基本示例
class Test extends Controller {
constructor(App) {
const Routes = [
{
url: '/hello',
execute: this.world
}
];
super({ Routes });
};
world(req, res) {
return res.json({success: true, msg: "Hello World."});
}
}
控制器类
class Controller {
constructor({ Routes }) {
// I want to be able to access the items from the Routes Object here so I can loop over them and initialize them
}
}
我需要一种方法将此路由对象传递给 Controller 类,它需要具有 URL,以便如果路由具有诸如/hello/:id
then 之类的参数,它将在那里定义,并且它需要知道在 Test 类中执行哪个函数。
问题是在调用 super 之前您不允许访问this
参数,并且您也无法在 super 中访问它。有什么办法可以让这个对象通过吗?
这是可能的还是我错过了一些非常明显的东西
解决方案
将您的路线定义为 astatic const routes
并将构造函数中的子类传递为
super(Test)
从父级,您可以在构造函数中访问
constructor(Test) {
this.routes = Test.routes
}
这应该可以解决问题。
推荐阅读
- next.js - vercel 无服务器函数调用超时
- swift - 仅显示最近的错误 架构 x86_64 的 4 个重复符号
- visual-studio - Visual Studio - 配置转换会破坏 XML 格式
- qt - 支持命令行的 Qt6 安装程序
- python - 在保留标题的同时附加 2 个数据集
- gitlab - 如何在 .gitlab-ci.yml 中连接另一个变量?
- mysql - Mysql ID 用逗号分隔,加入
- python - 在 Python 中获取修改时间作为不同的凭据
- powershell - 如何使用 Powershell 调用可执行文件,但不等待它完成?
- django - django 中的 CSRF 问题