[英]NodeJS Accessing an object in the parent class constructor from the Child Class
我正在嘗試的是創建一個 Controller Class 它將使用 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."});
}
}
Controller Class
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
}
}
我需要一種方法將此路由 Object 傳遞到 Controller class,它需要具有 URL 以便如果路由具有諸如/hello/:id
之類的參數,那么它將在那里定義並且它需要知道在哪個 function 中執行測試 class。
問題是在調用 super 之前不允許您訪問this
參數,並且您也無法在 super 中訪問它。 有什么辦法可以打通這個object嗎?
這是可能的還是我遺漏了一些非常明顯的東西
將您的路線定義為static const routes
,並將構造函數中的子 class 作為
super(Test)
從父級,您可以在構造函數中訪問
constructor(Test) { this.routes = Test.routes }
這應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.