简体   繁体   中英

NodeJS Accessing an object in the parent class constructor from the Child Class

What I'm attempting is to create a Controller Class that will initialize all my routes for me with ExpressJS here's a basic example of what I have

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
  }
}

I need a way to pass this routes Object into the Controller class, It needs to have the URL so that if a route has params such as /hello/:id then that would be defined there and it needs to know which function to execute in the Test class.

The issue is Your not allowed to access the this parameter before the super has been called and you can't access it within the super either. Is there any way that I can get this object through?

Is this possible or am I missing something really obvious

Define your routes as a static const routes and pass the child class in the constructor as

super(Test)

From the parent, you can access in the constructor

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

This should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM