ES6类定义方法的两种式及调用方式-class - function
2种定义类方法方法调用建议写法
在express,koa2中使用es6类进行编码,其中对方法调用的使用与说明
2种定义类方法
class WechatUserController {
// 方式一,常规定义方式
refresh(ctx){
console.log(ctx)
}
login = async (ctx) => {
this.save(ctx);
this.refresh(ctx);
ctx.body = {
status: 200,
msg: '成功',
}
}
// 方式二,箭头函数定义方式
save = async (ctx) => {
let body = {
nickName: ctx.headers.nickname,
openid: ctx.headers.openid,
loginCount: 1
}
let r = await new WechatUserModel(body).save()
return r.toJSON()
}
}
module.exports = new WechatUserController();
方法调用
const Router = require('koa-router');
const controller = require('../controllers/wechatUser.controller')
router.post('/login', controller.login)
module.exports = router;
此时类的实例调用方法会报一个错误,是发生在方法的内部调用自身的方法产生的错误, refresh方法不存在。 Cannot read property 'refresh' of undefined
原因在于用这种方式进行定义的方法,其内部 this 的具体指向需要等到运行时才会进行动态的绑定。
建议写法
1. 编码时建议使用方式二,箭头函数定义方式
2. 或者将方法定义为静态方法进行调用,示例:
class WechatUserController {
// 方式一,常规定义方式
static refresh(ctx){
console.log(ctx)
}
login = async (ctx) => {
this.save(ctx);
WechatUserController.refresh(ctx);
ctx.body = {
status: 200,
msg: '成功',
}
}
}
参考阅读
发表评论