首页 > 解决方案 > javascript中无法访问构造函数实例中的函数值

问题描述

构造函数“this.A”创建实例,然后将其发送到构造函数“this.b”。一个数组由两个构造函数实例编译而成。无法从存储它们的数组中访问来自“this.b”实例的值。收到“无法获取未定义的属性 'calc'”错误。然而,在数组被填充后,可以在最后访问值。这是过时的,因为 'var data' 是无穷无尽的值流,因此数组会不断被填充。

var data = [-1,1,4,3,-3,-4,1,-4];

function init() {
  this.A = function(value, time) {
    this.value = value;
    this.time = time
  }
  this.B = function(point, array) {
    this.calc = function() {
      var x = point.value;
        if(x>=0){
          return 'positive'
        } else {
          return 'negative'
        }
    }
  }
  this.time = 0;
  this.arrayA = [];
  this.arrayB = [];
}

function update (datastream) {
    var time = this.time += 1;
    var value = datastream[time];
    var x = new this.A(value, time);
    var y = new this.B(x, this.arrayA);
    this.arrayA.push(x);
    this.arrayB.push(y);
    //error:
    console.log(this.arrayB[time].calc())
}

function finish() {
  for(let x=0; x < data.length; x++) {
    console.log(this.arrayB[x].calc())
  }
}

init();
for(let x=0; x < data.length; x++) {
  update(data)
};
finish()

标签: javascriptconstructorundefined

解决方案


好的,所以在你第一次运行你推送到 arrayB 的更新函数时,它里面有一个项目。由于您正在使用 time 变量访问数组,因此它应该等于 0 以获取数组中的第一项。但是,您在函数开始时将时间变量加一。所以你试图访问一个不存在的项目,因此你得到了 undefined 并试图在 undefined 上调用 calc 函数。

console.log(this.arrayB[time - 1].calc())

推荐阅读