Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an undefined "this" when using Classes/Async Await [duplicate]

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();
like image 348
cusejuice Avatar asked Nov 14 '17 16:11

cusejuice


1 Answers

If you want this to always point to the instance in makeRequest, bind its context in the constructor:

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);
  }
}
like image 179
TimoStaudinger Avatar answered Sep 19 '22 00:09

TimoStaudinger