我正在尝试与 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
}
}
最佳答案
您还可以将回调函数的范围绑定(bind)到服务对象。
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));
}
关于javascript - chrome.serial.connect 回调范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27069639/