javascript - 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()
解决方案
好的,所以在你第一次运行你推送到 arrayB 的更新函数时,它里面有一个项目。由于您正在使用 time 变量访问数组,因此它应该等于 0 以获取数组中的第一项。但是,您在函数开始时将时间变量加一。所以你试图访问一个不存在的项目,因此你得到了 undefined 并试图在 undefined 上调用 calc 函数。
console.log(this.arrayB[time - 1].calc())
推荐阅读
- jquery - jQuery - 按选定的 SKU 编号返回项目
- flutter - Flutter 中的卡片视图和布局
- r - How to extract values from data that are imported using ReactiveFileReader?
- javascript - 自定义标记函数如何与 JavaScript 中的标记模板字符串一起使用?
- sqlite - Lisp cl-dbi - how to embed control characters in sqlite queries
- angular - My Angular 7 app is telling me 'The selector ... did not match any elements'
- javascript - Ajax request not working using differnt version of php
- r - Creating a time series plot and converting numeric data to date
- google-drive-api - Java 的 Drive API 客户端库是否在代号 1 中起作用
- linux - 当使用 memfd_create 系统调用时,内存分配在哪里?