我正在尝试使用“已配置的对象”作为ExpressJS中的控制器,因此我可以重用一堆代码。
取自快速配置:
var ctrl = new CRUDServiceAdapter(serviceConfig);
// list
// this works: ctrl.load()
app.get(serviceURL, ctrl.load);
另外,这是对象定义的一部分:
function CRUDServiceAdapter(serviceConfig){
this.config = serviceConfig;
this.logger = logModule.logger("service.controller." + serviceConfig.modelName);
};
CRUDServiceAdapter.prototype.load = function(req, res, next){
this.logger.debug("Creating an object model for " + this.config.modelName);
res.json({"msg": "Hello World"});
};
当通过expressJS请求调用方法时,我观察到对象属性this.config
是undefined
。但是如果我直接在对象上调用它,就像在注释ctrl.load()
中那样 - 配置对象按预期填充。
为什么对象在作为路径执行时会丢失它的属性值?
有没有办法解决它?
答案 0 :(得分:2)
背景丢失了:
您没有将对象ctrl
作为参数传递,只传递一个方法,因此该方法被称为任何常规函数,因此this
不指向ctrl(我猜它是未定义的),所以尝试更改代码:
app.get(serviceURL, ctrl.load.bind(ctrl));