-
使用 koa2 路由
const myClass = require('../controllers/myClass); router.get('/api/a', myClass.getA);
-
使用 class 编写 controller
class MyClass { constructor() { this.a = 'xxx'; } getA(ctx) { ctx.body = this.a; } } module.exports = new MyClass();
我简单模拟了一下我的代码场景,然后就发现这样使用路由会出现错误 TypeError: Cannot read property 'a' of undefined
。想请教下大家为什么会这样,如果这种写法不可避免会出现这种问题,那么大家是怎么写的?
这是 js 基础问题,this 指向问题;
当路由进入后,你的 'getA' 是一个函数,此时 this 指向全局(非严格模式),undefined(严格模式);
四种解决方案 :
1,router.get('/api/a', myClass.getA.bind(myClass))
2,router.get('/api/a', ctx => myClass.getA(ctx))
3,
4,