[英]Calling a class method from a callback function in JS
我對 JS 中“this”的范圍有疑問。
我有一個調用方法(connectSensor)的回調函數。 在該方法中,我嘗試使用“this”更改類的成員。 但是,我得到
“類型錯誤:無法讀取未定義的屬性 '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 的范圍無關。 我真誠地后悔浪費了大家的時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.