【问题标题】:Values from functions in constructor instances cannot be accessed in javascriptjavascript中无法访问构造函数实例中的函数值
【发布时间】:2018-08-23 13:24:18
【问题描述】:

构造函数“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()

【问题讨论】:

    标签: javascript constructor undefined


    【解决方案1】:

    问题在于您的数组索引。在您的“更新”功能中,您首先增加“时间”。这意味着您实际上跳过了数据流中的第一个条目,并直接进入第二个条目。当您在 ArrayA 和 ArrayB 上推送值时,它们存储在比您从数据流中提取的索引低 1 处。

    简而言之,您应该在更新函数结束时增加时间,而不是之前。您可以通过将此行更改为

    来快速验证这是真的
    this.arrayB[time - 1].calc()
    

    【讨论】:

    • 非常感谢,非常简单的修复。我将 this.time = 0 更改为 -1 并且效果很好。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 2020-07-11
      • 2012-08-21
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多