【问题标题】:Calling a class method from a callback function in JS从JS中的回调函数调用类方法
【发布时间】:2020-09-04 14:47:21
【问题描述】:

我对 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();

【问题讨论】:

  • 你确定peripheral不是undefined吗?
  • 我想是的。当我评论“this.connectSensor();”时,程序会打印“发现传感器”。并留在那里。当我取消注释时,我得到了错误,但有趣的是,消息没有打印出来。我不确定为什么。 (我不得不承认我不知道 JE 引擎是如何工作的)。
  • 所以“传感器”是在回调中定义的,因为在使用“this.sensor.name”时我没有收到“...未定义”错误,但在“connectSensor”中,“this "(无论它指的是什么)没有“传感器”成员/未定义。
  • 你用的是什么版本的node和noble?您可以分别使用node -vnpm ls noble 进行检查。
  • ""this"(无论它指的是什么)没有“传感器”成员/未定义。” connectSensorthis 的值是多少?

标签: javascript node.js callback this


【解决方案1】:

我现在意识到问题在于我的代码(但不是问题)中的 connectSensor 在“if”语句之外。因此,要发现的第一个 BLE 设备(它从来不是预期的传感器)没有初始化“传感器”成员,因此出现了错误。最后,这与“this”或 JavaScript 的范围无关。 我真诚地后悔浪费了大家的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2016-05-31
    相关资源
    最近更新 更多