Reputation: 111
I am having an issue with adding a method to an object in javascript. The following code should return a number but instead returns NaN. Hope you can help
function people(name, age){
this.name = name;
this.age = age;
this.numYearsLeft = pension();
}
function pension(){
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);
Upvotes: 2
Views: 102
Reputation: 4168
In order to call a function you need to put (). console.log(andrews.numYearsLeft);
should be console.log(andrews.numYearsLeft());
Also on
function pension(){
numYears = 65 - this.age;
return numYears;
}
this.age is undefined, thus the NaN.
(EDITED) Maybe try:
function people(name, age){
var that = this;
this.name = name;
this.age = age;
this.numYearsLeft = function(){
numYears = 65 - that.age;
return numYears;
};
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft());
Upvotes: 0
Reputation: 206028
You could use a prototypal model - making pension
a Method of people
:
function people(name, age){
this.name = name;
this.age = age;
this.numYearsLeft = this.pension(); // note the `this`
}
people.prototype.pension = function(){ // note the `prototype`
var numYears = 65 - this.age;
return numYears;
};
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft); // 37
Using prototype
your pension
method will inherit the constructor's (people
) properties (allowing you to refer using the this
keyword).
Another benefit of this is that, on every new
instantiation of people
you'll not recreate new instances / recalls of the pension
method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Upvotes: 5
Reputation: 207501
If you add a console.log() line inside of pension you will see that this
is the window and not the people object. One way to change this
would be to use call().
this.numYearsLeft = pension.call(this);
Example:
function people(name, age) {
this.name = name;
this.age = age;
this.numYearsLeft = pension.call(this);
}
function pension() {
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);
Other option is make it part of the people prototype.
function people(name, age) {
this.name = name;
this.age = age;
this.numYearsLeft = this.pension();
}
people.prototype.pension = function () {
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);
Upvotes: 2
Reputation: 17973
JavaScript works on a "function scope", so in short you're in the wrong scope. You need to either bind the "this" variable or create a function on the people class using the prototype property.
You can define it as a prototype function instead
people.prototype.pension = function() {
numYears = 65 - this.age;
return numYears;
}
Upvotes: 2