我希望整理一下我的项目,现在我尝试使用es6类来管理路由。但我的问题是this始终为undefined。
var express = require('express');
var app = express();
class Routes {
constructor(){
this.foo = 10
}
Root(req, res, next){
res.json({foo: this.foo}); // TypeError: Cannot read property 'foo' of undefined
}
}
var routes = new Routes();
app.get('/', routes.Root);
app.listen(8080);
_.bindAll(object, *methodNames)
,因此在您的示例中应使用_.bindAll(routes, 'Root')
。 - Craig Myles