我确定我失踪了一些小事,我会第一个告诉你我没有Angular或ES6专家。我有以下代码集:
getScanner(){
var that = this;
cordova.plugins.barcodeScanner.scan(
function (result) {
console.log("OBJ "+result);
that.data = result;
//THIS IS DEFINED
console.log("That data first is "+that.data);
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
//THIS IS UNDEFINED
console.log("That data is finally "+that.data);
}
正如您在上面看到的那样,当我第一次在回调中设置that.data时,它会很好地打印到控制台。然后,一旦我到达Cordova电话之外的console.log,它就会失去参考。我做错了什么?
答案 0 :(得分:5)
cordova.plugins.barcodeScanner.scan
调用是异步的,因此在调用成功回调之后才会定义that.data
。
如果您查看控制台,您应该注意到"That data is finally"
消息在 "That data first is"
消息之前已记录