簡體   English   中英

如何將匿名函數變量分配給類方法變量?

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

我正在嘗試通過使用coap包來實現與coap服務器的通信。 我的目標是獲取響應(在coap.request() response事件處理程序中),然后將其傳遞給其他變量和函數。

事件: 'response'

 function (response) { } 

在收到response時發出。 response是IncomingMessage一個實例。

如果observe指定的標志, 'response'事件將返回的實例ObserveReadStream 根據觀察規范,它們代表來自服務器的更新。

我創建了類someClass ,其中包含serverRequest()方法。

方法serverRequest() coap.request()強制性選項參數(用於設置coap.request()請求選項)和可選參數,用於根據需要設置消息正文。 此方法的目的是向服務器發送請求並返回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;
  }
}

我發送消息並成功獲取響應,但是匿名函數中的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將始終屬於函數,方法或匿名函數的范圍,兩者仍然是函數。

因此,為了保留對類作用域的引用,我將類方法的作用域中的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關鍵字,我沒有任何問題,腳本產生了相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM