Node.js express中间件中模块实例的访问

Node.js express中间件中模块实例的访问,node.js,express,middleware,Node.js,Express,Middleware,我想要一个节点模块,它导出一个返回类函数实例的工厂 //myModule.js function MyClass(options) { this.options = options || {}; } MyClass.prototype.handle = function(req, res, next) { //I want to access the instance here in the middleware function console.log(this.op

我想要一个节点模块,它导出一个返回类函数实例的工厂

//myModule.js
function MyClass(options) {
    this.options = options || {};
}

MyClass.prototype.handle = function(req, res, next) {
    //I want to access the instance here in the middleware function
    console.log(this.options);
}

module.exports = function(options) {
    return new MyClass(options);
}
然后,在server.js中,我附加了以下中间件:

var myInstance = require("./myModule")({
    foo: "bar"
});

app.use(myInstance.handle);

在中间件函数中,这指的是其他东西(可能是全局对象?),但我想访问包含选项的实例。我能想到的唯一解决方案是调用
myInstance.handle.bind(myInstance)
,但这对模块的用户来说不太友好。有没有其他方法可以解决这个问题,或者有没有更好的方法可以完全实现这种模式?

最好尽可能避免使用原型,并且您可以使用类似的方法实现您正在做的事情:

module.exports = function(opts) {

    // private methods/vars
    var options = opts || {};

    return {
      handle: function(req, res, next) {
        console.log(opts);
      }
    }
}