javascript - 使用类/异步等待时获取未定义的 "this"

标签 javascript ecmascript-6 async-await hapi.js ecmascript-2017

<分区>

我刚刚开始尝试类和异步等待。我正在使用 Node 版本 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
    //}
});

原型(prototype)示例

function Example() {
  this.a = 'a';
  this.b = 'b';
}

Example.prototype.fn = function() {
  console.log(this); // this works here
}

const ex = new Example();
ex.fn();

最佳答案

如果您希望this 始终指向makeRequest 中的实例, bind its context在构造函数中:

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);
  }
}

关于javascript - 使用类/异步等待时获取未定义的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290709/

相关文章:

javascript - 谷歌可视化 - TypeError : Cannot read property 'DataTable' of undefined [Chrome specific]

JavaScript 集合和值对象

javascript - 将 api 响应推送到 .map() 中的全局变量以某种方式使数据无法访问

c# - 从头开始异步处理

c# - 非阻塞和重复发生的生产者/消费者通知程序实现

c# - 在 ASP.NET 中轮询 Google Big Query 结果期间调用 Thread.Sleep 是否合适?备择方案?

javascript - 如何在 Canvas 中的形状后面留下痕迹?

JavaScript onClick函数触发ActionsScript3事件

javascript - jQuery $.post() 请求除非运行两次否则不起作用

javascript - 返回 Promise 而不是异步