cus*_*ice 7 javascript async-await ecmascript-6 hapijs ecmascript-2017
我刚刚开始尝试类和异步等待。我使用的是 Node 版本 8.9.0 (LTS)。当 I 时console.log(this)
,我得到undefined
而不是对对象的引用。
子处理程序.js
class Handler {
constructor(props) {
this.defaultRes = {
data: successMessage,
statusCode: 200
};
}
async respond(handler, reply, response = this.defaultRes) {
console.log(this); // why is `this` undefined????
try {
await handler;
return reply(response.data).code(response.statusCode)
} catch(error) {
return reply(error);
}
}
}
class SubHandler extends Handler {
constructor(props) {
super(props);
this.something = 'else';
}
makeRequest(request, reply) {
console.log(this); // why is `this` undefined!!
// in this case, doSomeAsyncRequest is a promise
const handler = doSomeAsyncRequest.make(request.params);
super.respond(handler, reply, response);
}
}
module.exports = new SubHandler;
Run Code Online (Sandbox Code Playgroud)
哈皮路线内
const SubHandler = require('./subhandler');
server.route({
method: 'GET',
path: '/',
handler: SubHandler.makeRequest,
// handler: function (request, reply) {
// reply('Hello!'); //leaving here to show example
//}
});
Run Code Online (Sandbox Code Playgroud)
原型示例
function Example() {
this.a = 'a';
this.b = 'b';
}
Example.prototype.fn = function() {
console.log(this); // this works here
}
const ex = new Example();
ex.fn();
Run Code Online (Sandbox Code Playgroud)
Tim*_*imo 13
如果要this
始终指向 中的实例makeRequest
,请在构造函数中绑定其上下文:
class SubHandler extends Handler {
constructor(props) {
super(props);
this.makeRequest = this.makeRequest.bind(this)
this.something = 'else';
}
makeRequest(request, reply) {
console.log(this);
const handler = doSomeAsyncRequest.make(request.params);
super.respond(handler, reply, response);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4112 次 |
最近记录: |