我开始使用自定义对象以及JavaScript中的自定义方法。为了练习,我写了一个小脚本来比较两个利率。起初我认为程序工作,虽然只是为了确定,使用document.write(John_Interest_Value),并收到NaN警报。我正确使用自定义方法吗?任何人都可以发现问题吗? 感谢。
function SimpleInterest (principal,time1,rate) {
this.principal = principal;
this.time1 = time1;
this.rate = rate;
this.interest = calculate_interest;
}
function calculate_interest(principal,time1,rate) {
var si;
var si = (principal*rate*time1)/100;
return si;
}
var tom_interest = new SimpleInterest(1000,3,.08);
var john_interest = new SimpleInterest(2000,3,.04);
var Tom_interest_value = tom_interest.interest();
var John_interest_value = john_interest.interest();
window.alert (John_interest_value);
if (Tom_interest_value > John_interest_value) {
document.write("Tom's interest earned is more than that of John's");
} else if (Tom_interest_value < John_interest_value){
document.write("John's interest earned is more than that of Tom's");
} else {
document.write("Tom and John earn equal interest");
}
答案 0 :(得分:1)
undefined*undefined
等于NaN
根据你选择打电话的方式:
var Tom_interest_value = tom_interest.interest();
var John_interest_value = john_interest.interest();
函数calculate_interest
内的变量未定义。
所以,正如你所写的那样,你需要做
var Tom_interest_value = tom_interest.interest(tom_interest.principal, tom_interest.time1, tom_interest.rate);
正如您所看到的那样,打字很乏味。
你想从calculate_interest
中删除参数,而是引用下面的对象变量
function calculate_interest() {
var si = (this.principal*this.rate*this.time1)/100;
return si;
}