我确信这是我失踪的小事,我会第一个告诉你我不是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,它就会失去参考.我究竟做错了什么?
该cordova.plugins.barcodeScanner.scan
调用是异步的,因此that.data
在调用成功回调之后才会定义.
如果您查看控制台,您应该注意到在"That data is finally"
消息之前记录了"That data first is"
消息.