使用类/异步等待时获取未定义的“this”[重复]

Posted

技术标签:

【中文标题】使用类/异步等待时获取未定义的“this”[重复]【英文标题】:Getting an undefined "this" when using Classes/Async Await [duplicate] 【发布时间】: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 问题。像here 和here 和here 和here 可能还有许多其他问题。 async/await 是 ES2017 的一部分,而不是 ES7 (ES2016) 【参考方案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 语义和大多数其他行为仍然相同。

以上是关于使用类/异步等待时获取未定义的“this”[重复]的主要内容,如果未能解决你的问题,请参考以下文章

等待异步函数导致未定义

在第一次调用时获取未定义的结果[重复]

使用轴和 Vue.js 进行异步/等待调用 - `.then()` 回调未更新 `this.something`

异步/等待,XHR 请求后返回的变量未定义

如何使节点 fs 与类异步/等待?

异步/等待类构造函数