Reputation: 389
I began working with custom objects along with custom methods in JavaScript. For practice I wrote a small script to compare two interest rates. At first I thought the program worked, although just to be sure, used document.write(John_Interest_Value), and received a NaN alert. Am I using custom methods correctly? Can anyone identify the problem? Thanks.
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");
}
Upvotes: 0
Views: 40
Reputation: 1877
undefined*undefined
equals NaN
Given the way you chose to call the below:
var Tom_interest_value = tom_interest.interest();
var John_interest_value = john_interest.interest();
The variables inside of the function calculate_interest
are undefined.
So, as you have written it you would need to do
var Tom_interest_value = tom_interest.interest(tom_interest.principal, tom_interest.time1, tom_interest.rate);
As you can see, typing that is tedious.
you want to remove the parameters from calculate_interest
and instead reference the objects variables like below
function calculate_interest() {
var si = (this.principal*this.rate*this.time1)/100;
return si;
}
Upvotes: 1