I've just started to experiment with classes and async await. I'm using Node version 8.9.0 (LTS). When I console.log(this)
, I get undefined
instead of the reference to the object.
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;
Inside Hapi route
const SubHandler = require('./subhandler');
server.route({
method: 'GET',
path: '/',
handler: SubHandler.makeRequest,
// handler: function (request, reply) {
// reply('Hello!'); //leaving here to show example
//}
});
Prototype 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();
No comments:
Post a Comment