我使用的是Ionic v2和Phonegap条形码扫描仪插件。
当执行下面的scanBarcode()函数时,我得到了错误:
Uncaught TypeError: Cannot set property 'test' of null
在
this.test = result.text;
代码:
import {Page} from 'ionic-angular';
@Page({
templateUrl: 'build/pages/scanBarcode/scanBarcode.html'
})
export class ScanBarcode {
constructor() {
this.test = "";
}
scanBarcode(){
cordova.plugins.barcodeScanner.scan(
function (result) {
console.log(result.text);
this.test = result.text;
console.log("SB result" + test);
},
function (error) {
alert("Scanning failed: " + error);
}
)
}
}
第一个console.log没有错误,并显示了正确的信息:
console.log(result.text);
代码的问题是您试图访问扫描方法的结果函数中类的"this"指针。
要解决此问题,请执行以下操作:
scanBarcode(){
//Create 'self' variable outside the scan function, assigning 'this' to it
let self = this;
cordova.plugins.barcodeScanner.scan(
function (result) {
console.log(result.text);
//Use 'self' instead of 'this' to access 'test'
self.test = result.text;
console.log("SB result" + test);
},
function (error) {
alert("Scanning failed: " + error);
}
)
}
解释
当你调用.scan()函数时,你会给它两个回调。您不能使用"this"来完成您想要的内容,因为在Javascript中,"this"具有函数调用方的上下文。
通常,当您在回调中访问"this"时,它具有"window"上下文。这是因为当你(定义和)调用一个没有对象上下文的函数时,你实际上是在使用"窗口"上下文。示例:
function fun(){ console.log('this = window; in here');
fun();
实际情况是:
window.fun = function() { /* ... */ }
window.fun();
(有关此方面的更多信息,请阅读javascript基于原型的面向对象模型)
在这种情况下,您将出现无法设置未定义错误的属性"test"。但是,由于您的回调是由cordova插件直接调用的,我相信"this"根本没有上下文(不过我不确定)。
无论如何,由于回调不是用类实例上下文调用的,因此"this"不代表类的实例,因此没有"test"属性。
最后,由于回调是一个闭包,并且闭包会记住创建它的环境,所以回调知道"self"变量的存在。这就是为什么你可以在这种情况下使用它。