此类用于扩展我的 expressjs 应用程序中的所有 Controller :
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);
我认为这是因为当我将函数作为参数传递时范围丢失了。我该如何解决这个问题?
最佳答案
使用bind绑定(bind)作用域的方法,像这样
this.app.get(APISLUG + this.name, this.all.bind(this));
关于javascript - ES6 类,传递函数作为参数来注册 expressjs 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35814872/