1

Newbie alert. I'm new to JavaScript. Love it so far. I'm having a bit of a problem I hope someone can help me with:

Here's my script in a .js file:

function human(name, age, gender){
  this.name = name;
  this.age = age;
  this.gender = gender;
  this.yearsToRetirement = function(){                  
          return 65 - this.age;

  };
}


var Steve = new human('Steve', 34, 'Male');
document.write(Steve.name + "  " + Steve.age + "  " + Steve.gender + Steve.yearsToRetirement);

But here's my browser output:

Steve 34 Malefunction (){ return 65 - this.age; }

As you may have guessed, I'm looking for there to be a "31" where we see function (){ return 65 - this.age; }

...What gives?

Any help is MUCH appreciated.

1
  • yearsToRetirement is a method of an object, so you have to call it with Steve.yearsToRetirement() Commented Oct 2, 2015 at 16:46

3 Answers 3

1

As yearsToRetirement is a function you want to execute it. Try this

var Steve = new human('Steve', 34, 'Male');
document.write(Steve.name + " " + Steve.age + " " + Steve.gender + Steve.yearsToRetirement());
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it through getter. Then, Steve.yearsToRetirement works fine.

function human(name, age, gender){
  this.name = name;
  this.age = age;
  this.gender = gender;
  var _yearsToRetirement = 65 - this.age;
  Object.defineProperties(this, {
        yearsToRetirement: {
            get: function () {
                return 65 - this.age;
            },
            enumerable: true
        }
    });  
}


var Steve = new human('Steve', 34, 'Male');
document.write(Steve.name + "  " + Steve.age + "  " + Steve.gender + Steve.yearsToRetirement + "<br>");

Steve.age = 40;
document.write(Steve.name + "  " + Steve.age + "  " + Steve.gender + Steve.yearsToRetirement);

Comments

0

You are getting yearsToRetirement as a function object here and not running it:

document.write(Steve.name + "  " + Steve.age + "  " + Steve.gender + Steve.yearsToRetirement);

Instead, you need to call the function, like this:

document.write(Steve.name + "  " + Steve.age + "  " + Steve.gender + Steve.yearsToRetirement());

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.