![](/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.