提问人:m278 提问时间:9/4/2020 最后编辑:m278 更新时间:9/5/2020 访问量:204
在 JS 中从回调函数调用类方法
Calling a class method from a callback function in 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();
答:
0赞
m278
9/5/2020
#1
我现在意识到问题是我的代码中的connectSensor(但不在问题中)在“if”语句之外。因此,要发现的第一个 BLE 设备(从来都不是预期的传感器)没有初始化“传感器”成员,因此会出现错误。归根结底,这与“this”或 JavaScript 的范围无关。 我真诚地后悔浪费了大家的时间。
评论
peripheral
undefined
node -v
npm ls noble
this
connectSensor