如何解决从JS中的回调函数调用类方法
我对JS中“ this”的范围有疑问。
我有一个调用方法(connectSensor)的回调函数。在这种方法中,我尝试使用'this'更改类的成员。但是我得到了
“ TypeError:无法读取未定义的属性'removeAllListeners()'”。
我认为,因为该方法是从回调内部调用的,所以'this'不再引用该类,但是我不知道如何解决它(即在connectSensor内部引用了该类)。我正在使用RPi 4和Linux。
/* Perhipheral MAC. */
const SENSOR_MAC = "aa:aa:aa:aa:aa:aa";
class ble{
constructor(){
this.noble = require('noble');
this.sensor;
}
createEventHandlers(){
var noble = this.noble;
noble.on('stateChange',function(state)
{
/* Start scanning if Bluetooth is on. */
if( state == 'poweredOn' ) noble.startScanning();
});
noble.on('discover',function(peripheral){
if (perhipheral.address == SENSOR_MAC){
noble.stopScanning();
this.sensor = peripheral;
console.log("Discovered the sensor: " + this.sensor.name)
/* Here 'this' is bound to the class. */
this.connectSensor();
}
}.bind(this));
}
connectSensor(){
/* I want 'this' here to always refer to the class. */
this.sensor.removeAllListeners();
}
}
用法:
bleClass = new ble();
bleClass.createEventHandlers();
解决方法
我现在意识到问题是我的代码中的connectSensor(而不是问题中的问题)不在“ if”语句之外。因此,要发现的第一个BLE设备(从来没有使用过预期的传感器)没有初始化“传感器”成员,因此没有错误。最后,这与“ this”或JavaScript的范围无关。 我真心地浪费每个人的时间。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。