此类用于扩展expressjs应用程序中的所有控制器:
import response from '../utils/responseParser.js';
const APISLUG = '/api/v1/';
export default class BaseController {
constructor(name, app, model){
this.model = model;
this.app = app;
this.name = name;
console.log(model);
this.register();
}
register() {
this.app.get(APISLUG + this.name, this.all);
}
/*
Retrive all records
*/
all(req, res, next) {
this.model.all(req.body, (err, data) => {
if(err) return res.json(response.replyError(data));
return res.json(response.reply(data));
});
}
}
正如你所看到的,我已经做了一个"寄存器"自动设置所有基本路线的方法。
我在这一行收到错误unable to read property " model " of undefined "
:
this.app.get(APISLUG + this.name, this.all);
我认为这是因为当我将函数作为参数传递时范围会丢失。我该如何解决这个问题?
答案 0 :(得分:13)
使用bind方法绑定范围,如此
this.app.get(APISLUG + this.name, this.all.bind(this));
答案 1 :(得分:4)
您可以将箭头功能设置为类的属性。箭头函数在词法上绑定this
值(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)。
在你的例子中:
export default class BaseController {
...
all = (req, res, next) => { // This is the only line that changed
...
}
}
请注意,类上的箭头函数不是标准的ES6语法,但可能会附带ES7(这里的注释中有一些注释:https://stackoverflow.com/a/31362350/2054731)。您可能需要将项目配置为能够使用此功能和/或其他ES7功能。