简体   繁体   English

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

[英]How to assign anonymous function variables to class method variables?

I'm trying to implement communication with coap server by using coap package . 我正在尝试通过使用coap包来实现与coap服务器的通信。 My goal is to get response (in coap.request() response event handler) and then pass it to other variables and functions. 我的目标是获取响应(在coap.request() response事件处理程序中),然后将其传递给其他变量和函数。

Event: 'response' 事件: 'response'

 function (response) { } 

Emitted when a response is received. 在收到response时发出。 response is an instance of IncomingMessage . response是IncomingMessage一个实例。

If the observe flag is specified, the 'response' event will return an instance of ObserveReadStream . 如果observe指定的标志, 'response'事件将返回的实例ObserveReadStream Which represent the updates coming from the server, according to the observe spec. 根据观察规范,它们代表来自服务器的更新。

I've created class someClass , which contains serverRequest() method. 我创建了类someClass ,其中包含serverRequest()方法。

Method serverRequest() takes mandatory options argument (which sets request options for coap.request() ) and optional argument which sets message body if needed. 方法serverRequest() coap.request()强制性选项参数(用于设置coap.request()请求选项)和可选参数,用于根据需要设置消息正文。 Purpose of this method is to send a request to server and return response , which is instance of coap.IncomingMessage . 此方法的目的是向服务器发送请求并返回response ,该responsecoap.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;
  }
}

I send message and obtain response successfully, however response variable inside anonymous function seems to be unique and different from response variable inside serverRequest method. 我发送消息并成功获取响应,但是匿名函数中的response变量似乎是唯一的,并且与serverRequest方法中的response变量不同。

Question: How can I pass variables from anonymous functions to other scopes? 问题:如何将变量从匿名函数传递到其他作用域?

You can call your method inside the body of an anonymous function: 您可以在匿名函数的主体内调用方法:

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

Edit based on comments: Using var that = this; 根据注释进行编辑:使用var that = this; is a common way to cheat the scope. 欺骗范围的一种常见方法。 this will always belong to the scope of a function, method or anonymous, both are still functions. this将始终属于函数,方法或匿名函数的范围,两者仍然是函数。

Therefore to keep a reference to the class scope, I assign the this from the class method's scope to var that so that when this changes to the anonymous' function scope, we still have access to it. 因此,为了保留对类作用域的引用,我将类方法的作用域中的this分配给var that以便当this更改为匿名函数作用域时,我们仍然可以访问它。

In ECMAscript 6 and above when using arrow functions, the this keyword is not re-bound and we don't have to cheat the scope. 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;
    });
  }        
}

Edit made by question author: 问题作者所做的编辑:

I didn't have problems by using this keyword, script produced same results. 通过使用this关键字,我没有任何问题,脚本产生了相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM