-1

Im learning javascript and run into this problem where I want to combine objects and functions. I have the following which, according to me, should lead to 65 - the age I inserted. I get nothing however.

Any thoughts on what Im doing wrong?

<script type="text/javascript">
function person(name, age) {
this.name = name;
this.age = age;
this.yearsUntilRetire = yearsLeft;
}
function yearsLeft {
var numYears = 65 - this.age;
return numYears;
}
var Marc = new person("Marc", 23);
document.write(Marc.yearsUntilRetire());
</script> 
asked Oct 10, 2014 at 13:17
2
  • 1
    Tip: Add the function to the person prototype for improved performance when creating multiple instances Commented Oct 10, 2014 at 13:24
  • 1
    The casing of your variable names should be backwards: var marc = new Person() Commented Oct 10, 2014 at 13:24

3 Answers 3

2

You're just missing parenthesis in the function declaration :

function yearsLeft() {

To fix this kind of errors, you must look at the errors in the console. The line where the syntax error happens is shown.

Recommended reading : Chrome Developer Tools

answered Oct 10, 2014 at 13:19
Sign up to request clarification or add additional context in comments.

Comments

1

You forgot () in the yearsLeft declaration!

<script type="text/javascript">
function person(name, age) {
this.name = name;
this.age = age;
this.yearsUntilRetire = yearsLeft;
}
function yearsLeft() {
var numYears = 65 - this.age;
return numYears;
}
var Marc = new person("Marc", 23);
document.write(Marc.yearsUntilRetire());
answered Oct 10, 2014 at 13:22

Comments

0

There could be two errors, if you look at your console, it could be that you are missing () immediately after yearsleft function declaration. and you are trying to write out Marc.yearsUntilRetire() instead of Marc.yearsUntilRetire. I think yearsUntilRetire is a variable that takes the number of years returned from yearsLeft and not a function.

<script type="text/javascript">
function person(name, age) {
this.name = name;
this.age = age;
this.yearsUntilRetire = yearsLeft;
}
function yearsLeft {
var numYears = 65 - this.age;
return numYears;
}
var Marc = new person("Marc", 23);
document.write(Marc.yearsUntilRetire());
</script> 
answered Oct 10, 2014 at 13:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.