使用类/异步等待时获得未定义的“this”

cus*_*ice 7 javascript async-await ecmascript-6 hapijs ecmascript-2017

我刚刚开始尝试类和异步等待。我使用的是 Node 版本 8.9.0 (LTS)。当 I 时console.log(this),我得到undefined而不是对对象的引用。

子处理程序.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;
Run Code Online (Sandbox Code Playgroud)

哈皮路线内

const SubHandler = require('./subhandler');

server.route({
    method: 'GET',
    path: '/',
    handler: SubHandler.makeRequest,
    // handler: function (request, reply) {
    //  reply('Hello!'); //leaving here to show example
    //}
});
Run Code Online (Sandbox Code Playgroud)

原型示例

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

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

const ex = new Example();
ex.fn();
Run Code Online (Sandbox Code Playgroud)

Tim*_*imo 13

如果要this始终指向 中的实例makeRequest,请在构造函数中绑定其上下文

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 不,类不会在 JavaScript 中自动绑定它们的成员函数。 (2认同)
  • `class` 主要是对 JS 已经拥有多年的基于原型的继承的语法糖。`this` 语义和大多数其他行为仍然相同。 (2认同)