如何继承Express路由器并在里面调用super方法

How to inherit Express router and also call super inside method?

本文关键字:在里面 调用 super 方法 路由器 Express 何继承 继承      更新时间:2023-09-26

Express Router我想要"继承"/扩展的功能

var proto = module.exports = function(options) {
  var opts = options || {};
  function router(req, res, next) {
    router.handle(req, res, next);
  }
  // mixin Router class functions
  router.__proto__ = proto;
  router.params = {};
  router._params = [];
  router.caseSensitive = opts.caseSensitive;
  router.mergeParams = opts.mergeParams;
  router.strict = opts.strict;
  router.stack = [];
  return router;
};

所以目的是创建我自己的函数/类来扩展这个express路由器并覆盖route方法以接受额外的参数,但也能够调用express路由器的super.route

我已经尝试了几种方法,包括util.inherits,但没有工作。

如果可能的话,也请提供一些解释

最终目标是这样的:

var testRouter = express.Router();
testRouter.route('/test-route', 'aaa' /* my extra param here */)
    .get(controller.testWhatever)

能够重写route方法来添加新参数,但保留旧功能

认为这个例子解释了你在寻找什么

// Create a class
function Vehicle(color){
  this.color = color;
}
// Add an instance method
Vehicle.prototype.go = function(){
  return "Underway in " + this.color;
}
// Add a second class
function Car(color){
  this.color = color;
}
// And declare it is a subclass of the first
Car.prototype = new Vehicle();
// Override the instance method
Car.prototype.go = function(){
  return Vehicle.prototype.go.call(this) + " car"
}
// Create some instances and see the overridden behavior.
var v = new Vehicle("blue");
v.go() // "Underway in blue"
var c = new Car("red");
c.go() // "Underway in red car"