Ionic V2和Cordova插件-未捕获类型错误:无法设置属性'测试'为null
Ionic V2 and Cordova Plugins - Uncaught TypeError: Cannot set property 'test' of null
我使用的是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"变量的存在。这就是为什么你可以在这种情况下使用它。
相关文章:
- Javascript使用变量设置属性
- 如何在自动完成时设置属性标题
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 未捕获的类型错误:无法设置属性'背景'的未定义
- 无法设置属性'innerHTML'在javascript中为null
- Haxe Javascript:在不使用Reflect的情况下按名称获取和设置属性
- Jquery为每个元素设置属性
- 从骨干集合筛选模型,然后为这些模型设置属性
- 我们可以设置属性'id'到不同的'按钮'通过使用javascript或jquery的循环
- 如何在javascript对象中设置属性的类型,就像mongoose模式设计一样
- emscripten+sdl=引发异常:TypeError:无法设置属性'widthNative'的未定
- 未捕获的类型错误:无法设置属性'onclick'为null.已尝试window.onload
- Backbone JS Promises在模型上设置属性之前解析
- Highcharts无法设置属性'的值;要点':对象为null或未定义
- 无法设置属性'round'的未定义
- 通过 Javascript 设置 C# 属性值
- 在 app.locals 上设置属性和调用 app.set() 有什么区别?
- 不引人注目地设置属性后函数失败
- j查询在设置属性后在后续单击时不读取数据属性
- IE错误:无法设置属性'的值;样式':对象为null或未定义