我正在尝试与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
}
}
答案 0 :(得分:2)
您也可以将回调函数的范围绑定到服务对象。
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));
}
答案 1 :(得分:0)
我通过在此函数调用
之前将范围保存在局部变量中来解决这个问题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!
}
}