![](/img/trans.png)
[英]How to access method variables from within an anonymous function in JavaScript?
[英]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
,該response
是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
將始終屬於函數,方法或匿名函數的范圍,兩者仍然是函數。
因此,為了保留對類作用域的引用,我將類方法的作用域中的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.