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>
3 Answers 3
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
Comments
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());
Comments
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>
var marc = new Person()