javascript - Ionic V2 和 Cordova 插件 - 未捕获的类型错误 : Cannot set property 'test' of null

标签 javascript ionic-framework cordova-plugins ionic2

我正在使用 Ionic v2 和 Phonegap Barcode Scanner plugin .

在执行下面的 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 的基于原型(prototype)的面向对象模型)

在这种情况下,您会遇到无法设置未定义属性“测试” 错误。但是,由于您的回调是由 cordova 插件直接调用的,所以我相信“this”根本没有上下文(不过我不确定)。

无论如何,由于没有使用您的类实例上下文调用回调,“this”不代表您的类的实例,因此没有“测试”属性。

最后,由于回调是一个闭包,并且闭包会记住创建它的环境,所以回调知道“self”变量的存在。这就是您可以在这种情况下使用它的原因。

关于javascript - Ionic V2 和 Cordova 插件 - 未捕获的类型错误 : Cannot set property 'test' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36334924/

相关文章:

cordova - Ionic Native Date Picker 不适用于 Android

ionic-framework - switchToLocationSettings()后如何检测gps是否启用?

javascript - 如何使零数值算作真值?

javascript - 如何在kinetic.js中跟踪动画帧数?

javascript - 在 jQuery 和 Javascript 之间使用 JSON 数据

javascript - 在 React js 中实现搜索

angularjs - Ionic/Cordova 应用中的 Facebook Account Kit

angularjs - 标记仅显示 JSON 数组中的最后一个元素

ios - cordova 3.4.0 使用 paypal 插件

java - Cordova PhoneGap Android 回调与数据