【发布时间】:2018-04-27 16:37:04
【问题描述】:
我刚刚开始尝试使用类和异步等待。我正在使用节点版本 8.9.0 (LTS)。当我console.log(this) 时,我得到undefined 而不是对对象的引用。
subhandler.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;
哈皮路线内
const SubHandler = require('./subhandler');
server.route({
method: 'GET',
path: '/',
handler: SubHandler.makeRequest,
// handler: function (request, reply) {
// reply('Hello!'); //leaving here to show example
//}
});
原型示例
function Example() {
this.a = 'a';
this.b = 'b';
}
Example.prototype.fn = function() {
console.log(this); // this works here
}
const ex = new Example();
ex.fn();
【问题讨论】:
-
你怎么打电话给
makeRequest? -
从 Hapi 路由处理程序hapijs.com/tutorials/routing调用
-
对于此类问题,通常会在调用中缺少
.bind(this)。 -
async/await是 ES2017 的一部分,而不是 ES7 (ES2016)
标签: javascript ecmascript-6 async-await hapijs ecmascript-2017