0

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");
}
1
  • You almost have the function part right with calculate_interest, although you don't need the first line var si; (you only need to initialize it once). What are you trying to accomplish with the SimpleInterest function, though? Commented Jun 20, 2014 at 2:14

1 Answer 1

1

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;
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.