如何将匿名函数变量分配给 class 方法变量?

How to assign anonymous function variables to class method variables?

我正在尝试通过使用 coap package. My goal is to get response (in coap.request() response 事件处理程序来实现与 coap 服务器的通信,然后将其传递给其他变量和函数。

Event: 'response'

function (response) { }

Emitted when a response is received. response is an instance of IncomingMessage.

If the observe flag is specified, the 'response' event will return an instance of ObserveReadStream. Which represent the updates coming from the server, according to the observe spec.

我创建了 class someClass,其中包含 serverRequest() 方法。

方法serverRequest()采用强制选项参数(设置coap.request()) and optional argument which sets message body if needed. Purpose of this method is to send a request to server and return response, which is instance of coap.IncomingMessage的请求选项)。

const coap = require('coap');

class someClass {
  constructor(someOption) {
    this.someOption = someOption;
  }

  serverRequest(options, messageBody=undefined) {
    const request = coap.request(options);
    let response;
    request.on('response', res => {
      console.log(response); // undefined
      response = res;
      console.log(response);  // valid response
    });
    if (messageBody !== undefined) {
      request.write(messageBody);
    }
    request.end();
    console.log(response);  // undefined
    return response;
  }
}

我发送消息并成功获得响应,但是匿名函数中的 response 变量似乎是唯一的并且不同于 serverRequest 方法中的 response 变量。

问题:如何将变量从匿名函数传递到其他作用域?

您可以在匿名函数体内调用您的方法:

class Test 
{
  constructor(someOption) {
    this.someOption = someOption;
  }

  myMethod ( data ) {
    //.. do something
  }

  anotherMethod() {
    var data = {answer:42};
    var that = this;
    functionWithCallback( function(differentOption) {
      that.myMethod(data);
      that.someOption = differentOption;
    });
  }       
}

根据评论编辑: 使用 var that = this; 欺骗 作用域的常用方法。 this永远属于函数、方法或匿名的范围,两者仍然是函数。

因此,为了保留对 class 作用域的引用,我将 class 方法作用域中的 this 分配给 var that,这样当 this更改匿名函数范围,我们仍然可以访问它。

ECMAscript 6及以上使用箭头函数时,this关键字不会重新绑定,我们不必欺骗范围。

class Test 
{
  constructor(someOption) {
    this.someOption = someOption;
  }

  myMethod ( data ) {
    //.. do something
  }

  anotherMethod() {
    var data = {answer:42};
    functionWithCallback( (differentOption) => {
      this.myMethod(data);
      this.someOption = differentOption;
    });
  }        
}

问题作者编辑:

我使用 this 关键字没有问题,脚本产生了相同的结果。