chrome.serial.connect 回调范围问题

chrome.serial.connect callback scope issues

本文关键字:范围 问题 回调 connect serial chrome      更新时间:2023-09-26

我正在尝试与Chrome应用程序中的串行设备进行通信。我遇到的问题是来自chrome.serial函数的回调在错误的范围内。如果我将所有内容都放在全局范围内,一切都在工作,但是如果我尝试在"类"中调用任何东西,那么什么都不会发生。

service = {};
service.state = "disconnected";
service.connect = function(){
    chrome.serial.connect(service.config.port, options, function (connectionInfo) {
        console.log("Connected"); // This works
        service.state = 'connected'; // This doesn't change the variable
        this.state = 'connected'; // This also doesn't change it
    }
}

您也可以将回调函数的作用域绑定到服务对象。

service = {};
service.state = "disconnected";
service.connect = function() {
    chrome.serial.connect(this.config.port, options, function (connectionInfo) {
        console.log("Connected"); // This works
        this.state = 'connected';
    }.bind(this));
}

我通过在此函数调用之前将范围保存在局部变量中来解决此问题

service = {};
service.state = "disconnected";
service.connect = function(){
    var scope = this;
    chrome.serial.connect(service.config.port, options, function (connectionInfo) {
        console.log("Connected"); // This works
        service.state = 'connected'; // This doesn't change the variable
        this.state = 'connected'; // This also doesn't change it
        scope.state = 'connected'; // This works!
    }
}