Nodejs,表示路由为es6类

我想清理我的项目,现在我尝试使用es6类为我的路线。 我的问题是总是未定义的。

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); 

尝试使用代码来钉住this

 app.get('/', routes.Root.bind(routes)); 

您可以使用下划线bindAll函数退出样板。 例如:

 var _ = require('underscore'); // .. var routes = new Routes(); _.bindAll(routes) app.get('/', routes.Root); 

我还发现,es7允许你用更优雅的方式编写代码:

 class Routes { constructor(){ this.foo = 10 } Root = (req, res, next) => { res.json({foo: this.foo}); } } var routes = new Routes(); app.get('/', routes.Root); 

这是因为你已经通过一个方法作为一个独立的函数来expression。 Express不知道它来自哪个类,所以当你的方法被调用时,它不知道这个值是什么。

你可以强制bind this值。

 app.get('/', routes.Root.bind(routes)); 

或者您可以使用替代构造来pipe理路线。 对于没有类的面向对象编程,您仍然可以使用很多语法优势。

 function Routes() { const foo = 10; return { Root(req, res, next) { res.json({ foo }); } }; } const routes = Routes(); app.get('/', routes.Root); app.listen(8080); 
  • 你不必担心这个价值
  • 这个函数是否被new调用并不重要
  • 您可以避免在每个路由上调用bind的复杂性

这里有一个很好的资源清单,为什么ES6类不如他们看起来那么好。

上面的答案似乎有点复杂。 检查我在这里做了什么:

 class Routes { constructor(req, res, next) { this.req = req; this.res = res; this.next = next; this.foo = "BAR" // Add more data to this. here if you like } findAll (){ const {data, res,} = this; // Or just reference the objects directly with 'this' // Call functions, do whaterver here... // Once you have the right data you can use the res obejct to pass it back down res.json ({foo: this.foo}); // Grabs the foo value from the constructor } } 

现在说到使用这个类,你可以做一些事情:

 var express = require('express'); var router = express.Router(); var {Routes} = require('./Routes'); router.get('/foo', (req, res, next) => { new Routes(req, res, next).findAll(); }); 

我会分开这两个文件,所以你只需要Routes类到您的Router文件。

希望这有助于!

或者,如果你不喜欢绑定每个路由的上下文,你可以select将它绑定到类的构造函数本身的方法。

例如:

 constructor() { this.foo = 10; this.Root = this.Root.bind(this); }