简体   繁体   English

从 JS 中的回调函数调用类方法

[英]Calling a class method from a callback function in JS

I'm having problem with the scope of 'this' in JS.我对 JS 中“this”的范围有疑问。
I have a callback function that calls a method (connectSensor).我有一个调用方法(connectSensor)的回调函数。 In that method, I try to change a member of the class using 'this'.在该方法中,我尝试使用“this”更改类的成员。 However, I get但是,我得到
"TypeError: Cannot read property 'removeAllListeners()' of undefined". “类型错误:无法读取未定义的属性 'removeAllListeners()'”。
I think because the method is called from inside the callback, 'this' no longer refers to the class, but I don't know how to solve it (ie have a reference to the class inside connectSensor).我认为因为该方法是从回调内部调用的,'this' 不再指代该类,但我不知道如何解决它(即对 connectSensor 内部的类进行引用)。 I'm using RPi 4 and Linux.我正在使用 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();
}

}

Usage:用法:

bleClass = new ble();
bleClass.createEventHandlers();

I now realize the problem was that the connectSensor in my code (but not in the question) was outside the "if" statement.我现在意识到问题是我的代码中的 connectSensor(但不在问题中)在“if”语句之外。 Therefore, the first BLE device to be discovered (which was never the intended sensor) did not have the "sensor" member initialized, and hence the error.因此,第一个被发现的 BLE 设备(从来不是预期的传感器)没有初始化“传感器”成员,因此出现错误。 In the end this had nothing to do with the scope of 'this' or JavaScript.最后,这与“this”或 JavaScript 的范围无关。 I sincerely regret wasting everybody's time.我真诚地后悔浪费了大家的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM