2-5课中关于generator函数的this
来源:
杨洋1989
2016-08-01
function*(next){ console.log(this,this.query); var token = config.token; var timestamp = this.query.timestamp; var nonce = this.query.nonce; var str = [token,timestamp,nonce].sort().join(''); var signature = this.query.signature; var echostr = this.query.echostr; var sha = sha1(str); if (sha === signature) { this.body = echostr + ''; }else{ this.body = 'wrong'; }
以上代码中,控制台输出了this和this.query,分别如下
this:
{ request: { method: 'GET', url: '/?signature=e2f78f94a2bb2b36a9ccca893b9995c62ef2a52f&echostr=7219047515058761727×tamp=1469984654&nonce=477653313', header: { 'user-agent': 'Mozilla/4.0', accept: '*/*', host: 'yangyang.ngrok.cc', pragma: 'no-cache', connection: 'Keep-Alive' } }, response: { status: 404, message: 'Not Found', header: {} }, app: { subdomainOffset: 2, proxy: false, env: 'development' }, originalUrl: '/?signature=e2f78f94a2bb2b36a9ccca893b9995c62ef2a52f&echostr=7219047515058761727×tamp=1469984654&nonce=477653313', req: '<original node req>', res: '<original node res>', socket: '<original node socket>' }
this.query
{ signature: 'bff7d1d12ea1cc28a01bf5b2b17e15a5ecc83b3', echostr: '5159695744898153955', timestamp: '1469985058', nonce: '1470577093' }
发现this对象为何并无query属性?
通过给this.body赋值实现响应,这其中的工作机理是什么?
写回答
1回答
-
这个并不是工作机理,只是 Javascript 的语法而已,对象属性的函数绑定,koa 里面构建对象是通过这种方式构建的,可以运行下这段代码:
var obj = { get query () { return {a: 1} } } console.log (obj) console.log (obj.query)
深入了解的话,可以看下相关文档:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/get
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Object_initializer
以及去读下 koa 的源码:
https://github.com/koajs/koa/blob/master/lib/request.js#L147
012016-08-01
相似问题