【问题标题】:Getting an undefined "this" when using Classes/Async Await [duplicate]使用类/异步等待时获取未定义的“this”[重复]
【发布时间】: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)
  • 听起来像是一个基本的 JS this 问题。像herehereherehere 可能还有许多其他问题。
  • async/await 是 ES2017 的一部分,而不是 ES7 (ES2016)

标签: javascript ecmascript-6 async-await hapijs ecmascript-2017


【解决方案1】:

如果你想让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);
  }
}

【讨论】:

  • 嗯,这行得通,但我在这里遗漏了什么吗?我认为this 可以使用新的 ES6 类关键字开箱即用。所以基本上,对于类的所有方法来获得对this 的引用,我必须在构造函数中绑定它的上下文?看起来很奇怪
  • 不,类不会在 JavaScript 中自动绑定其成员函数。
  • class 主要是 JS 多年来基于原型的继承的语法糖。 this 语义和大多数其他行为仍然相同。
猜你喜欢
  • 1970-01-01
  • 2020-09-13
  • 2022-01-22
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 2019-08-07
相关资源
最近更新 更多