首页 > 解决方案 > 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/:idthen 之类的参数,它将在那里定义,并且它需要知道在 Test 类中执行哪个函数。

问题是在调用 super 之前您不允许访问this参数,并且您也无法在 super 中访问它。有什么办法可以让这个对象通过吗?

这是可能的还是我错过了一些非常明显的东西

标签: javascriptnode.jsexpress

解决方案


将您的路线定义为 astatic const routes并将构造函数中的子类传递为

super(Test)

从父级,您可以在构造函数中访问

constructor(Test) { this.routes = Test.routes }

这应该可以解决问题。


推荐阅读