简体   繁体   中英

Values from functions in constructor instances cannot be accessed in javascript

Constructor 'this.A' creates instances that are then sent to constructor 'this.b'. An array is compiled of both constructor instances. Values from 'this.b' instances cannot be accessed from the array they are stored in. An 'Unable to get property 'calc' of undefined' error is received. Values can however be accessed at the end after the array has been filled. This is obsolete as 'var data' is an endless stream of values so the arrays are constantly being filled.

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()

The problem is in your array indexing. In your "update" function you start by incrementing "time". This means you are actually skipping over the first entry in your datastream, and going directly to the second. When you push values on your ArrayA and ArrayB, they are stored at an index 1 lower than you are pulling from your datastream.

In short, you should increment time at the end of your update function, not before. You can quickly verify that this is true by changing this line to

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

Ok, so on your first run through the update function you pushed to arrayB so it has one item in it. Since you are accessing the array with the time variable it should be equal to zero to get the first item in the array. However, you add one to the time variable at the start of the function. So you're trying to access an item that doesn't exist, hence you're getting undefined and trying to call the calc function on undefined.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM