这里是 JavaScript 新手,在对象引用方面遇到了一些困难。具体来说,我正在尝试创建一个对象构造函数,该构造函数具有访问对象属性的各种方法。
就上下文而言,这是为了计算能源使用量。
1)我执行各种计算来创建作为旧能源使用和新能源使用的参数传递的数组
2) 我有一个 Project 对象构造函数来构建一个项目,其中的变量将在所有对象中共享。
所以我会这样调用它:
var boilerUpgrade = new Project(oldKwh, newKwh, oldTherms, newTherms);
其中参数是值数组。
//build an object constructor for each project
function Project(oldKwh, newKwh, oldTherms, newTherms){
//create arrays for the old & new energy usages
this.oldKwh = oldKwh;
this.newKwh = newKwh;
this.kwhSaved = [];
this.totalKwhSaved;
this.oldTherms = oldTherms;
this.newTherms = newTherms;
this.thermsSaved = [];
this.totalThermsSaved;
this.oldMMBtu = [];
this.newMMBtu = [];
this.MMBtuSaved = [];
this.totalMMBtuSaved;
this.electricCostSaved = [];
this.totalElectricCostSaved;
this.thermsCostSaved = [];
this.totalThermsCostSaved;
this.costSaved = [];
this.totalCostSaved; //...
}
在对象内,我还创建了许多方法,例如:
//create method to calculate MMBtu savings
this.energyCalcs = function(){
for (var i =0; i<12; i++){
this.oldMMBtu[i] = (this.oldKwh[i]*(3412.3/1000000)) + (this.oldTherms[i]*(1000/1000000));
this.newMMBtu[i] = (this.newKwh[i]*(3412.3/1000000)) + (this.newTherms[i]*(1000/1000000));
this.thermsSaved[i] = this.oldTherms[i] - this.newTherms[i];
this.kwhSaved[i] = this.oldKwh[i] - this.newKwh[i];
this.MMBtuSaved[i] = this.oldMMBtu[i]-this.newMMBtu[i];
this.totalThermsSaved += this.thermsSaved[i];
this.totalKwhSaved += this.kwhSaved[i];
this.totalMMBtuSaved += this.MMBtuSaved[i];
}
};
但是,该方法以“this.myArray”的方式引用的对象中的数组似乎显示为未定义,而没有先前计算的值。
这里缺少一两个关键概念,说明为什么对象中的方法不能使用“this.myArray”语法来访问值。对我缺少的东西有什么想法吗?
最佳答案
您可以将方法分配给可以访问 this.* 属性的原型(prototype)。
类似这样的
function Person(name) {
this.name = name || 'Test User';
}
Person.prototype.sayHello = function() {
alert('Hello from' + this.name);
}
var test = new Person('Bob');
test.sayHello();
关于JavaScript:在方法中使用对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383870/